Java get compile-time safe method name

妖精的绣舞 提交于 2019-12-06 06:09:51

问题


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:


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.



来源:https://stackoverflow.com/questions/34121544/java-get-compile-time-safe-method-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!