vendredi 18 août 2017

How to use Method Reference operator to get the reference of method

I want to reference an annotation value in one class from another class. Like here -

class A {
    private static final String STATIC_STRING = B.class.getMethod("myMethod").getAnnotation(SomeAnnotation.class).name();
}

The problem here is that I cannot use this syntax because it requires getMethod to be wrapped in a try-catch which is not possible. Although I can use a static block to create this variable and just gulp the exception in catch block, I don't want to do that because if in future the method name is changed, compiler won't throw an error in the static block.

I was wondering if I could do something like

private static final String STATIC_STRING = (B::myMethod).getAnnotation(SomeAnnotation.class).name();

Note: neither B nor SomeAnnotation is my source, they come from another library.

I have 2 questions here

  • Is there a better way to get value from annotation, preferably without using any external library like Google Reflections or similar?
  • How can I use :: to get instance of java.lang.reflect.Method? Is it possible altogether? If yes, is vice-versa also possible, i.e. create supplier or mapper from Method's object?




Aucun commentaire:

Enregistrer un commentaire