簡體   English   中英

如何使用“方法引用”運算符獲取方法的引用

[英]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();

注意: BSomeAnnotation是我的來源,它們都來自另一個庫。

我在這里有2個問題

  • 是否有更好的方法從注釋中獲取價值,最好不使用任何外部庫(例如Google Reflections或類似的庫)?
  • 如何使用::來獲取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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM