如何获取类(Java)中所有方法的方法引用? [英] How to get Method Reference for all methods in a class (Java)?

查看:284
本文介绍了如何获取类(Java)中所有方法的方法引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法参考可以作为 Class :: Method 获得。但是如何获取类的所有方法的方法引用?

Method Reference for a specific method in Java 8 can be obtained as Class::Method. But how to get the method reference of all methods of a class?

所有需要的方法都有不同的方法名称,但相同的类型签名。此外,这些方法的名称在之前是未知

All the desired methods have different method names, but the same type signature. Also, the names of the methods is not known before hand.

示例:

class Test {
    public static double op0(double a) { ... }
    public static double op1(double a) { ... }
    public static double op2(double a) { ... }
    public static double op3(double a) { ... }
    public static double op4(double a) { ... }
}

对已知方法的方法引用 op0 可以获得:

The method reference to a known method op0 can be obtained as:

DoubleFunction<Double> f = Test::op0;

但是,如何获取类中所有方法的方法引用?

But, how to get the method references of all methods in the class?

推荐答案

没有反射可行的解决方案,因为现有方法的动态发现反射操作。但是,一旦发现方法并创建了方法引用实例(或其动态等价物),代码的实际调用将在没有反射的情况下运行:

There is no solution that works without Reflection as the dynamic discovery of existing methods is a reflective operation. However, once methods are discovered and a method reference instance (or the dynamic equivalent of it) has been created, the actual invocation of the code runs without Reflection:

class Test {
    public static double op0(double a) { ... }
    public static double op1(double a) { ... }
    public static double op2(double a) { ... }
    public static double op3(double a) { ... }
    public static double op4(double a) { ... }

    static final Map<String, DoubleUnaryOperator> OPS;
    static {
        HashMap<String, DoubleUnaryOperator> map=new HashMap<>();
        MethodType type=MethodType.methodType(double.class, double.class);
        MethodType inT=MethodType.methodType(DoubleUnaryOperator.class);
        MethodHandles.Lookup l=MethodHandles.lookup();
        for(Method m:Test.class.getDeclaredMethods()) try {
          if(!Modifier.isStatic(m.getModifiers())) continue;
          MethodHandle mh=l.unreflect(m);
          if(!mh.type().equals(type)) continue;
          map.put(m.getName(), (DoubleUnaryOperator)LambdaMetafactory.metafactory(
            l, "applyAsDouble", inT, type, mh, type).getTarget().invokeExact());
        } catch(Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
        OPS=Collections.unmodifiableMap(map);
    }
}

初始化类后,您可以调用特殊操作没有使用 OPS.get(name).applyAsDouble(doubleValue)或使用调用所有操作,例如

Once the class has been initialized, you can invoke a particular op without Reflection using OPS.get(name).applyAsDouble(doubleValue) or invoke all ops using, e.g.

OPS.forEach((name,op)-> System.out.println(name+'('+42+") => "+op.applyAsDouble(42)));

这篇关于如何获取类(Java)中所有方法的方法引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆