[英]Get the method name from a 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<String, Integer> sampleMethod, String input) {
Integer output = sampleMethod.apply(input);
System.out.println("Calling method "+ sampleMethod);
return output;
}
}
傳遞方法引用時,您必須考慮自己實際在做什么。 因為這:
Integer::getInteger
與此幾乎相同(使用以下方法,有一個堆棧層):
s -> Integer.getInteger(s)
上面再次類似於以下內容:
new Function<String, Integer> {
@Override
public Integer apply(String s){
return Integer.getInteger(s);
}
}
在最后一個代碼段中,您清楚地看到與被調用方法Integer#getInteger(String)
沒有邏輯連接。 這就解釋了為什么不引入新內容就不可能實現您的預期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.