【问题标题】:Get class name from static method reference [duplicate]从静态方法引用中获取类名 [重复]
【发布时间】:2016-08-04 07:12:11
【问题描述】:

用什么替换 foo()?

class MethodIteration {
  public static void main(String[] args) {
    for (MyFuncInt m : new MyFuncInt[] { Class1::method, Class2::method })
      System.out.println(m.getClass().foo()); // want Class1, Class2 etc here
  }
}

对不起,太简洁了。移动设备;)

我不认为这是上述问题的重复,因为我想在包含静态方法的类之外获取名称。如果我尝试m.getClass().getName(),我会得到“MethodIteration$$Lambda$1:[someHash]”。

【问题讨论】:

    标签: java reflection


    【解决方案1】:

    恐怕你不能。对Class1::methodClass2::method 的调用被封装在一个实现MyFuncInt 的lambda 闭包中,它没有访问封装类的方法(它甚至不是lambda 类的声明字段)。

    我会说你不能使用功能界面。您必须创建一个函子,向其传递对类的引用(或只是带有类名的字符串),以便稍后检索它:

    class MyFunctor implements MyFuncInt {
    
        public final Class<?> clazz;
        private final MyFuncInt func;
    
        public MyFunctor(Class<?> clazz, MyFuncInt func) {
            this.clazz = clazz;
            this.func = func;
        }
    
        @Override
        public void doSomething() {
            func.doSomething();     
        }
    }
    

    然后像这样实例化:

    new MyFunctor(Class1.class, Class1::method);
    

    【讨论】:

    • 这是“担心的”,但谢谢:)
    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2020-12-07
    • 2010-11-07
    相关资源
    最近更新 更多