Geo*_*his 1 java lambda java-8
是否可以获取java.util.function.Function的方法名称.我想每次都记录正在使用的方法的名称.下面的示例打印Lambda对象,但我还没有找到一种简单的方法来获取方法名称:
public class Example {
public static void main(String[] args) {
Example ex = new Example();
ex.callService(Integer::getInteger, "123");
}
private Integer callService(Function<String, Integer> sampleMethod, String input) {
Integer output = sampleMethod.apply(input);
System.out.println("Calling method "+ sampleMethod);
return output;
}
}
Run Code Online (Sandbox Code Playgroud)
传递方法引用时,您必须考虑,实际上在做什么.因为这:
Integer::getInteger
Run Code Online (Sandbox Code Playgroud)
几乎相同(有一个堆栈层更多与以下方法)对此:
s -> Integer.getInteger(s)
Run Code Online (Sandbox Code Playgroud)
以上再次类似于以下内容:
new Function<String, Integer> {
@Override
public Integer apply(String s){
return Integer.getInteger(s);
}
}
Run Code Online (Sandbox Code Playgroud)
在最后一个片段中,您清楚地看到与被调用方法没有逻辑连接Integer#getInteger(String).哪个解释为什么不引入新的东西就不可能做你想做的事.