是否有一种方法可以在Java方法中传递回调函数?

我试图模拟的行为是一个。net委托被传递给一个函数。

我看到有人建议创建一个单独的对象,但这似乎有点过分,但我意识到有时过度是做事的唯一方法。


当前回答

检查闭包是如何在lambdaj库中实现的。它们实际上有一个非常类似于c#委托的行为:

http://code.google.com/p/lambdaj/wiki/Closures

其他回答

如果你指的是。net匿名委托,我认为Java的匿名类也可以使用。

public class Main {

    public interface Visitor{
        int doJob(int a, int b);
    }


    public static void main(String[] args) {
        Visitor adder = new Visitor(){
            public int doJob(int a, int b) {
                return a + b;
            }
        };

        Visitor multiplier = new Visitor(){
            public int doJob(int a, int b) {
                return a*b;
            }
        };

        System.out.println(adder.doJob(10, 20));
        System.out.println(multiplier.doJob(10, 20));

    }
}

在Java 8中,这个任务很简单,如果你想在多线程场景中使用回调,你可以像下面这样做:

public  void methodA (int n, IntConsumer consumer) {
    
    // create a thread
    Thread t = new Thread(() -> {
        // some time consuming operation
        int result = IntStream.range(0, n).sum();
        // after the result is ready do something with it.
        consumer.accept(result);
    });
    t.start();
}

使用这个方法:

methodA(1000000, System.out::println);
public class HelloWorldAnonymousClasses {

    //this is an interface with only one method
    interface HelloWorld {
        public void printSomething(String something);
    }

    //this is a simple function called from main()
    public void sayHello() {

    //this is an object with interface reference followed by the definition of the interface itself

        new HelloWorld() {
            public void printSomething(String something) {
                System.out.println("Hello " + something);
            }
        }.printSomething("Abhi");

     //imagine this as an object which is calling the function'printSomething()"
    }

    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp =
                new HelloWorldAnonymousClasses();
        myApp.sayHello();
    }
}
//Output is "Hello Abhi"

基本上,如果你想让一个接口的对象 不可能,因为接口不能有对象。

选择是让某个类实现接口,然后使用该类的对象调用该函数。 但是这种方法非常冗长。

或者,编写新的HelloWorld() (*oberserve这是一个接口而不是一个类),然后接着定义接口方法本身。(*这个定义实际上是匿名类)。 然后获得对象引用,通过它可以调用方法本身。

这在Java 8中使用lambdas非常容易。

public interface Callback {
    void callback();
}

public class Main {
    public static void main(String[] args) {
        methodThatExpectsACallback(() -> System.out.println("I am the callback."));
    }
    private static void methodThatExpectsACallback(Callback callback){
        System.out.println("I am the method.");
        callback.callback();
    }
}

创建一个接口,并在回调类中创建相同的接口属性。

interface dataFetchDelegate {
    void didFetchdata(String data);
}
//callback class
public class BackendManager{
   public dataFetchDelegate Delegate;

   public void getData() {
       //Do something, Http calls/ Any other work
       Delegate.didFetchdata("this is callbackdata");
   }

}

现在在你想要回调的类中实现上面的Created Interface。 同时传递你的类的“this”对象/引用回调。

public class Main implements dataFetchDelegate
{       
    public static void main( String[] args )
    {
        new Main().getDatafromBackend();
    }

    public void getDatafromBackend() {
        BackendManager inc = new BackendManager();
        //Pass this object as reference.in this Scenario this is Main Object            
        inc.Delegate = this;
        //make call
        inc.getData();
    }

    //This method is called after task/Code Completion
    public void didFetchdata(String callbackData) {
        // TODO Auto-generated method stub
        System.out.println(callbackData);
    }
}