dimanche 6 décembre 2015

Java get compile-time safe method name

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 only one have any thoughts, comments, or a solution to this?

What I think would be the most elegant solution would be if Java auto built Enums for class names, fields, and methods. Then everyone could metaprogram in a compile-time safe way =)





Aucun commentaire:

Enregistrer un commentaire