Java equivalent of C# Delegates (queues methods of various classes to be executed)
Asked Answered
G

3

15

TLDR:

Is there a Java equivalent of C#'s delegates that will allow me to queue up methods of various classes and add them to the queue dynamically? Language constructs instead of the code for it.

Context:

I have used Unity 3D before and I love things like the Update method of scripts. Just declaring the method adds it to the list of methods executed each frame. I want to create something like that in my LWJGL game. For this, I would want to use delegates (or something equivalent to it). Is there any Java language construct that would allow me to do this? I would prefer answers that include two or more (so that I can pick and choose which will be the most optimal for my code) constructs and a way of using them. I don't want the code, I just want to know where to start. The most fun part of programming is working the problem out and I don't want to be deprived of that. Also, I don't want to be told EXACTLY how to do it. I want to be guided in the right direction instead of being thrown in that direction onto that destination. How would I learn? :-)

Gib answered 6/9, 2016 at 10:9 Comment(1)
The library safety-mirror adds delegates and events to Java. See https://mcmap.net/q/75832/-java-delegates, or better, the project's README: github.com/Hervian/safety-mirror.Casas
H
10

Extracted from https://msdn.microsoft.com/en-gb/library/aa288459(v=vs.71).aspx :

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.

That said, Java does not have delegates like C#. However, since Java 8, we do have some sort of function pointers by using method references and functional interfaces.

As you politely requested, I am not going to tell you exactly how to implement this code, but you should be able to come up with a solution with this information.

Hemiterpene answered 6/9, 2016 at 10:32 Comment(2)
This answer takes my request to the extreme but it doesn't give me the code I need... which is nice. However, an improvement for future questions like this is to not assume that I know about things like Interfaces and other intermediate (and beyond) skills as I now have to research about Interfaces etc. Just a suggestion for your future answers. Thank you btwGib
Thanks for your feedback! I will take it into account next time.Hemiterpene
D
29

Actually there is no exact counterpart for delegates in Java. But there are constructs that mimic their behavior.

Java 8

Functional interfaces

The concept that comes closes to delegates in Java 8 is that of functional interfaces.

For example, if you have a C# delegate:

delegate void Runnable();

in Java, you would create a functional interface like:

@FunctionalInterface
public interface Runnable {
    void run();
}

The nice thing about functional interfaces is they can be used easily in lambda expressions.

Example

So, let's suppose you have the following class:

public class SomeClass {
    public static void someStaticMethod() {
    }

    public void someMethod() {
    }
}

Lambda expressions and method references

With Java 8, you get lambda expressions.

List<Runnable> queue = new ArrayList<>();
queue.add(() -> someMethod());
queue.add(() -> someStaticMethod());

There is a short-hand named method reference for this, if you actually simply call a method:

List<Runnable> queue = new ArrayList<>();
queue.add(this::someMethod);
queue.add(SomeClass::someStaticMethod);

Java 7

With Java 7, the only thing you can use is anonymous classes:

List<Runnable> queue = new ArrayList<>();
queue.add(new Runnable() {
    public void run() {
        someMethod();
    }
});
queue.add(new Runnable() {
    public void run() {
        someStaticMethod();
    }
});

I hope this was not too much information, so you can still learn. ;-) However, I like my answer to be useful also for other people looking up this question.

Disinter answered 6/9, 2016 at 10:30 Comment(2)
Looking back on this a year and a bit later, I am still learning things from this answer due to actually understanding more of it and am questioning why I asked the question in the way I did (wanting to reinvent the wheel by requesting for little information). In particular, the method reference part is an interesting feature because it reminds me of c(++) namespace member access. You get a long overdue upvote :)Gib
@JamesYeoMan: Thanks for that :-) Yeah, actually StackOverflow is the place for providing good and quality answers and not for giving "hints" ;-) The C++ thingy is probably just a coincidence... They just needed a syntax in Java for method references and went for that.Disinter
H
10

Extracted from https://msdn.microsoft.com/en-gb/library/aa288459(v=vs.71).aspx :

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.

That said, Java does not have delegates like C#. However, since Java 8, we do have some sort of function pointers by using method references and functional interfaces.

As you politely requested, I am not going to tell you exactly how to implement this code, but you should be able to come up with a solution with this information.

Hemiterpene answered 6/9, 2016 at 10:32 Comment(2)
This answer takes my request to the extreme but it doesn't give me the code I need... which is nice. However, an improvement for future questions like this is to not assume that I know about things like Interfaces and other intermediate (and beyond) skills as I now have to research about Interfaces etc. Just a suggestion for your future answers. Thank you btwGib
Thanks for your feedback! I will take it into account next time.Hemiterpene
S
2

java function interface != c# delegate. From the consumers' side, you won't be able to get any detailed information other than a pure c-style function-pointer. You cannot tell whether a java function interface is binding some objects as a lambda expression or a member function, or just a static method with zero dependencies. I'd say c# delegate provides some very interesting features, may be not that important, to help diagnostic potential program defects like thread-safety of a delegate.

Semipostal answered 8/11, 2019 at 18:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.