从java.util.function.Function获取方法名称
是否可以获取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 sampleMethod, String input) { Integer output = sampleMethod.apply(input); System.out.println("Calling method "+ sampleMethod); return output; } }
在传递方法引用时,您必须考虑,实际上在做什么。 因为这:
Integer::getInteger
几乎相同(在下面的方法中有更多的堆栈层):
s -> Integer.getInteger(s)
以上再次类似于以下内容:
new Function { @Override public Integer apply(String s){ return Integer.getInteger(s); } }
在最后一个片段中,您清楚地看到与被调用方法Integer#getInteger(String)
没有逻辑连接。 哪个解释为什么不引入新的东西就不可能做你想要的。