Java get compile-time safe method name

2019-04-10 12:50发布

While working with the reflection class and annotations I have found that there is no clear way to reference a method name in a compile-time safe way. What I really want is to be able to reference a method within an annotation. Might look something like:

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

At the moment you can only do this with strings, which is not compile time safe.. This is a problem because it undermines Java being statically typed. The only solution I have found is something like what is below. However this still does not help with referencing a method in an 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 any thoughts, comments, or a solution to this?

1条回答
三岁会撩人
2楼-- · 2019-04-10 13:27

I write an AnnotationProcessor that can provide a compile-safe method reference. See it on github

It will give a compile error if the referenced method not exists.

And it works in eclipse, see the snapshot.

eclipse-use

查看更多
登录 后发表回答