Java get safe compile time method name

While working with the reflection class and annotations, I found that there is no clear way to reference the method name in a safe way to compile. I really want to be able to reference the method in the annotation. It might look something like this:

@CallAfter(method=Foo.class.foo())
void Bar() { ... }

Currently, you can only do this with strings that are not safe for compile time. This is a problem because it undermines the static typing of Java. The only solution I found seems to be the one below. However, this does not help when referencing a method in the annotation. :(

public static String methodName = null;

public static void main(String[] args) {

    // .foo() is compile-time safe
    loadMethodName(IFoo.class).foo();
    System.out.println(methodName);
}

public static <T> T loadMethodName(Class<T> mock) {
    return (T) Proxy.newProxyInstance(mock.getClassLoader(), new Class[] { mock }, 
    (obj, method, args) -> {
        methodName = method.getName();
        return null;
    });
}

public interface IFoo {
    Object foo();
}

Does anyone have thoughts, comments, or a solution?

+4
1

AnnotationProcessor, . github

, .

eclipse, . .

eclipse-use

+1

Source: https://habr.com/ru/post/1618809/


All Articles