从静态方法引用中获取类名 [英] Get class name from static method reference
问题描述
用什么代替 foo()?
What to replace foo() with?
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
}
}
抱歉,篇幅太短.移动设备;)
Sorry about brevity. Mobile device ;)
我不认为这是提到的问题的重复,因为我想在包含静态方法的类之外获取名称.如果我尝试 m.getClass().getName()
我得到MethodIteration$$Lambda$1:[someHash]".
I don't think it's a duplicate of mentioned question since I want to get the name while outside the class containing the static method. If I try m.getClass().getName()
I get "MethodIteration$$Lambda$1:[someHash]".
推荐答案
恐怕你不能.对 Class1::method
、Class2::method
的调用被封装在一个实现 MyFuncInt
的 lambda 闭包中,它没有方法来访问包装类(它甚至不是 lambda 类的声明字段).
I'm afraid you can't. The calls to Class1::method
, Class2::method
are wrapped inside a lambda closure that implements MyFuncInt
, which has no methods to access the wrapped class (it's not even a declared field of the lambda class).
我想说你不能使用函数式界面.您必须创建一个函子,向该函子传递对类的引用(或只是带有类名的字符串),以便稍后检索它:
I'd say you can't use a functional interface. You'd have to make a functor to which you pass a reference to the class (or just a string with the class name), so you can retrieve it later:
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);
这篇关于从静态方法引用中获取类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!