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 constru
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.
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.
Actually there is no exact counterpart for delegates in Java. But there are constructs that mimic their behavior.
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.
So, let's suppose you have the following class:
public class SomeClass {
public static void someStaticMethod() {
}
public void someMethod() {
}
}
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);
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.