1

So I have a question in relation to using custom annotations at runtime.

Let me fill you in on what I am trying to achieve. I have created a custom annotation and applied it to a method in a service class.

public class MyService 
{
    @MyCustomAnnotation
    public String connect()
    {
        return "hello";
    }
}

Now I can go and use reflection to process methods and apply some kind of logic to methods which have my custom annotation applied to them.

for(Method method : obj.getClass().getDeclaredMethods())        
{           
    // Look for @MyCustomAnnotation annotated method                
    if(method.isAnnotationPresent(MyCustomAnnotation.class))            
    {
        // Do something...
    }
}

However, I seem to be missing a piece of the puzzle as I can't figure out how to apply the reflection processing step automatically at runtime.

For example if I have the following main method in my application, how/where do I automatically apply the reflection processing step when I run the following?

public static void main(String[] args)
{
    MyService service = new MyService(); 
    service.connect();
}

Obviously this is possible as other frameworks such as spring are able to achieve it but I can't find an example of how they do this.

  • This annotation scan should be when Service is created or ready to use? You can scan all your classes at some point and apply this for them: http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection – Beri Apr 18 '17 at 12:07
  • @Beri - annotation scan? –  Apr 18 '17 at 14:47
  • 1
    Or an aspect: http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html. In a single application point you would simply call aspect to look for all methods with an annotation. – Beri Apr 18 '17 at 18:29
  • @Beri - yeah got it working with aspects. So the next question will be is there a simple way to add an aspect library to an existing project. –  Apr 19 '17 at 16:31

2 Answers2

0

Credit to @Beri

I used aspects to create a solution.

0

Reflection is useful if you need to do something at compile time, if you want to do something when the method is called, you should use Aspect Oriented Programming. The most common framework for Java is AspectJ.

I have a multimodule example here. It's an example with scala, but you can omit the scala dependencies and classes and implement it with Java. If you want to use the aspect in more than one place you must implement it in a separate module in order to include it and avoid repeating logic.

Motomine
  • 4,205
  • 5
  • 20
  • 23