4

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?

Soto
  • 611
  • 6
  • 19
  • I you can make Strings compile time safe if you add compile time checks via [annotation processing](http://hannesdorfmann.com/annotation-processing/annotationprocessing101/) similar to [this here](http://thecodersbreakfast.net/index.php?post/2009/07/09/Enforcing-design-rules-with-the-Pluggable-Annotation-Processor). – zapl Dec 06 '15 at 19:25
  • Unfortunately, no, there's no out-of-the-box way to do this. – chrylis -cautiouslyoptimistic- Dec 06 '15 at 19:32
  • Nice this would solve my problem. Kinda sucks I would have to go all the way out to annotation processing, but hey I guess if there is no other solution. Thank you for the advise and the links. – Soto Dec 06 '15 at 19:36
  • Possible duplicate of [Is there a way to use annotations in Java to replace accessors?](http://stackoverflow.com/questions/348408/is-there-a-way-to-use-annotations-in-java-to-replace-accessors) – Paul Sweatte Nov 21 '16 at 17:52

1 Answers1

2

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

Dean Xu
  • 4,438
  • 1
  • 17
  • 44