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

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

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


当前回答

从Java 8开始,有lambda和方法引用:

Oracle文档:Lambda表达式 Oracle文档:方法引用

例如,如果你想要一个功能接口a -> B,你可以使用:

import java.util.function.Function;

public MyClass {
    public static String applyFunction(String name, Function<String,String> function){
        return function.apply(name);
    }
}

你可以这样称呼它:

MyClass.applyFunction("42", str -> "the answer is: " + str);
// returns "the answer is: 42"

你也可以通过类方法。例如:

@Value // lombok
public class PrefixAppender {
    private String prefix;

    public String addPrefix(String suffix){
        return prefix +":"+suffix;
    }
}

然后你可以这样做:

PrefixAppender prefixAppender= new PrefixAppender("prefix");
MyClass.applyFunction("some text", prefixAppender::addPrefix);
// returns "prefix:some text"

注意:

这里我使用了函数接口Function<A,B>,但是包java.util.function中还有许多其他的接口。最值得注意的是

供应商:void -> 消费者:A ->无效 双消费者:(A,B) ->无效 功能:A -> B biffunction:(A,B) -> C

以及许多其他专门研究某些输入/输出类型的程序。然后,如果它不提供你需要的,你可以创建自己的FunctionalInterface:

@FunctionalInterface
interface Function3<In1, In2, In3, Out> { // (In1,In2,In3) -> Out
    public Out apply(In1 in1, In2 in2, In3 in3);
}

使用示例:

String computeAnswer(Function3<String, Integer, Integer, String> f){
    return f.apply("6x9=", 6, 9);
}

computeAnswer((question, a, b) -> question + "42");
// "6*9=42"

你也可以用抛出异常来实现:

@FunctionalInterface
interface FallibleFunction<In, Out, Ex extends Exception> {
    Out get(In input) throws Ex;
}
public <Ex extends IOException> String yo(FallibleFunction<Integer, String, Ex> f) throws Ex {
    return f.get(42);
}

其他回答

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这是一个接口而不是一个类),然后接着定义接口方法本身。(*这个定义实际上是匿名类)。 然后获得对象引用,通过它可以调用方法本身。

它有点旧了,但不管怎样……我发现Peter Wilkinson的答案很好,除了它不适用于像int/Integer这样的原始类型。 问题是参数[i]的. getclass(),它返回实例java.lang。整数,另一方面,getMethod(methodName,parameters[])不会正确解释(Java的错误)…

我结合了丹尼尔·斯皮沃克(Daniel Spiewak)的建议(在他的回答中);成功的步骤包括:捕捉NoSuchMethodException -> getMethods() ->通过method.getName() ->查找匹配的一个,然后显式遍历参数列表并应用Daniels解决方案,例如识别类型匹配和签名匹配。

我最近开始做这样的事情:

public class Main {
    @FunctionalInterface
    public interface NotDotNetDelegate {
        int doSomething(int a, int b);
    }

    public static void main(String[] args) {
        // in java 8 (lambdas):
        System.out.println(functionThatTakesDelegate((a, b) -> {return a*b;} , 10, 20));

    }

    public static int functionThatTakesDelegate(NotDotNetDelegate del, int a, int b) {
        // ...
        return del.doSomething(a, b);
    }
}

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

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);
        }
    }
}

最简单的方法是创建一个可重用模型并触发....https://onecompiler.com/java/3wejrcby2?fbclid=IwAR0dHbGDChRUJoCZ3CIDW-JQu7Dz3iYGNGYjxYVCPCWfEqQDogFGTwuOuO8