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

前端 未结 3 1713
野性不改
野性不改 2020-12-31 14:59

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

3条回答
  •  有刺的猬
    2020-12-31 15:47

    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 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 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 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.

提交回复
热议问题