How to create custom annotation with code behind

前端 未结 2 1437
死守一世寂寞
死守一世寂寞 2020-12-12 14:08

I would like to create my own custom annotation. My framework is Stand alone java application. When someone annotate his pojo class a \"hidden\" code behind will trigger m

2条回答
  •  無奈伤痛
    2020-12-12 14:38

    create an annotation something like this:

     public @interface MyMessageDriven{
     }
    

    And you have an interface that can apply annotation like this:

    public interface MyMessagListener {
    
        public void message();
    }
    
    
    
    @MyMessageDriven  
    public class MyMessage implements MyMessagListener  {
       public void message(){
         System.out.println(" I am executed")
       }
    } 
    

    Load the above class using classloader and using reflections check the annotation is presrent.

    if it is present, use loaded instance to execute it.

      Object obj = ClassLoader.getSystemClassLoader().loadClass("MyMessage").newInstance();
      MyMessagListener mml =  (MyMessagListener) obj;
      mml.message();
    

    Listener implementation you can put in MyMessage class or some other class that implements MessageListener.

    In this case, need to provide implementation for message() what it is going to do.

    But this class should be loaded and more important thing here is how your MyMessage class is loaded.

    That is based on the meta data present in the MyMessage class.Similar way, in the real time scenario as well this is how it works.

    Annotation is a metadata to a class that says based on the supplied data, do something.Had this metadata not present in the MyMessage class, you need not execute message() method.

    Hope this will help you.

提交回复
热议问题