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

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

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


当前回答

我发现使用反射库实现的想法很有趣,并提出了这个,我认为它工作得很好。唯一的缺点是丢失了传递有效参数的编译时检查。

public class CallBack {
    private String methodName;
    private Object scope;

    public CallBack(Object scope, String methodName) {
        this.methodName = methodName;
        this.scope = scope;
    }

    public Object invoke(Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Method method = scope.getClass().getMethod(methodName, getParameterClasses(parameters));
        return method.invoke(scope, parameters);
    }

    private Class[] getParameterClasses(Object... parameters) {
        Class[] classes = new Class[parameters.length];
        for (int i=0; i < classes.length; i++) {
            classes[i] = parameters[i].getClass();
        }
        return classes;
    }
}

你可以这样使用它

public class CallBackTest {
    @Test
    public void testCallBack() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        TestClass testClass = new TestClass();
        CallBack callBack = new CallBack(testClass, "hello");
        callBack.invoke();
        callBack.invoke("Fred");
    }

    public class TestClass {
        public void hello() {
            System.out.println("Hello World");
        }

        public void hello(String name) {
            System.out.println("Hello " + name);
        }
    }
}

其他回答

如果你指的是。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中还不是一级对象;不能将函数指针作为回调函数传递。相反,创建一个对象(通常实现一个接口),其中包含您需要的方法并传递该方法。

对于Java中的闭包(它将提供您正在寻找的行为)已经提出了建议,但在即将发布的Java 7中不会包含任何建议。

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中需要这种功能时,我通常使用观察者模式。它确实意味着一个额外的对象,但我认为这是一种干净的方式,而且是一种被广泛理解的模式,有助于提高代码的可读性。

有点吹毛求疵:

我听到有人建议创建一个 分开的物体,但看起来 过度

传递回调包括在几乎所有的OO语言中创建一个单独的对象,所以它几乎不能被认为是多余的。您的意思可能是,在Java中,它要求您创建一个单独的类,这比具有显式的一级函数或闭包的语言更冗长(也更消耗资源)。然而,匿名类至少减少了冗长,并且可以内联使用。