[英]How to use Method Reference operator to get the reference of method
我想從另一類引用一個類中的注釋值。 像這兒 -
class A {
private static final String STATIC_STRING = B.class.getMethod("myMethod").getAnnotation(SomeAnnotation.class).name();
}
這里的問題是我不能使用此語法,因為它要求將getMethod
包裹在try-catch
,這是不可能的。 盡管我可以使用static
塊來創建此變量,並且只是在catch
塊中吞下異常,但我不想這樣做,因為如果將來更改方法名稱,編譯器將不會在static
塊中引發錯誤。
我想知道我是否可以做類似的事情
private static final String STATIC_STRING = (B::myMethod).getAnnotation(SomeAnnotation.class).name();
注意: B
和SomeAnnotation
是我的來源,它們都來自另一個庫。
我在這里有2個問題
::
來獲取java.lang.reflect.Method
實例? 完全有可能嗎? 如果是,反之亦然,例如,從Method
的對象創建供應商或映射者? 對於第一個問題,您是否考慮過使用吸氣劑?
private static String getSomeAnnotationName() {
try {
return B.class.getMethod("myMethod").getAnnotation(SomeAnnotation.class).name();
} catch (NoSuchMethodException e) {
return null;
}
}
對於第二個問題,我認為不可能從::
獲取Method
。 這是因為從::
方法代表功能接口的實現,而不是真正的方法。 但是,相反的情況也是可能的。 您可以這樣創建一個lambda:
Consumer<SomeType> consumer = x -> {
try {
yourMethod.invoke(someObject, x)
} catch (...) {
// again you have to ignore the exceptions here, unfortunately
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.