小编Kin*_*ung的帖子

如何使用反射将 Lambda 表达式作为 JDK8 中的方法参数传递

在 JDK 8 中,我可以使用反射来调用带有 FunctionInterface 参数的方法,并传递 Lambda 表达式。例如,这有效。

import java.util.function.IntPredicate;  
import java.lang.reflect.Method;

public class LambdaReflect {

    public static void main(String args[]) {
        System.out.println(test(x->true));
        // Now do this in reflection
        Class<LambdaReflect> thisC = LambdaReflect.class;
        Method meths[] = thisC.getDeclaredMethods();
        Method m = meths[1];  // test method
        try {
            IntPredicate lamb = x->true;
            boolean result = (Boolean) m.invoke(null, lamb);
            System.out.println(result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static boolean test(IntPredicate func) {
        return func.test(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果参数类型仅在运行时已知,如何将 lambda 表达式传递给该方法?换句话说,如果我在编译时不知道方法的参数类型,而只知道它是一个函数式接口,我可以使用反射用lambda表达式来调用它吗?

java reflection lambda

4
推荐指数
1
解决办法
2444
查看次数

标签 统计

java ×1

lambda ×1

reflection ×1