mardi 18 avril 2017

java annotations - automated use at runtime

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.





Aucun commentaire:

Enregistrer un commentaire