1

I have a class A with a bunch of methods I have annotated the same with unique Annotations. I want to invoke the method at runtime given the specific annotation. Also, I might have to pass parameters as well.

public class XYZAccessor(){
    @CustomAnnotation(id="methodAIdentifier")
    public String methodA(){
        return "A";
    }
    @CustomAnnotation(id="methodBIdentifier")
    public String methodB(){
        return "B";
    }
    @CustomAnnotation(id="methodCIdentifier")
    public int methodC(int param){
        return (5+param);
    }
}

Given the string "methodAIdentifier", I would like to invoke XYZAccessor.methodA();

I have seen these approaches for the same.

1) Java Reflection: XYZAccessor.getClass.getMethods.getAnnotations() Iterate through that and find the specific method and invoke it.

2) Google Reflections: These have javaassist and guava as a dependancy. Use their framework Class.getMethodAnnotatedWith("methodAIdentifier")

3) AspectJ: I am not clear on how to use Aspect for this use case. Something like a pointcut and an @Around. Something like Pointcut matching methods with annotated parameters

Which of these approaches is the most efficient and the best approach to this problem?

Preaman
  • 151
  • 1
  • 1
  • 8
  • Assuming you want to do this more than once, the most efficient is to cache the method to be called. How you do that depends on your use case, but this can be many time faster. If you are only doing this a few times, I wouldn't worry about it and just do whatever you feel is simplest. – Peter Lawrey Jun 07 '17 at 15:03
  • Thanks @PeterLawrey as the method would be called multiple times. I will cache the methods and write my own implementation using reflection. – Preaman Jun 08 '17 at 07:28
  • I suggest using a ClassValue to cache your choices regarding annotation. This will effectively allow you to cache this data in a thread safe manner. – Peter Lawrey Jun 09 '17 at 10:32

0 Answers0