简体   繁体   中英

How can I pass the class name and method on which the annotaion being invoked as a "value" to the annotation attribute

 public class Demo {

     public Demo(){}

     @Annotaion(name = "DemoClass::method1")
     public void method1(params...)
     {

     }

}

I do not want to hardcode the "name" attribute, instead I need to pass it as something like this.getClass().getName().NAME_OF_THE_METHOD_ON_WHICH_INVOKED

First, create a custom annotation

@Retention(RetentionPolicy.RUNTIME) 
@interface Annotation { 
    public int value1(); 
    public int value2(); 
} 

Then use it

public class TestClass {
    @Annotation(value1 = 15, value2 = 30) 
    public static void test(){ 
            Class cl = TestClass.class; 
            Method[] allMethods = cl.getMethods(); 
            Method thisMethod = null;

            for (Method m : allMethods)
                if (m.getName().equals("test")) thisMethod = m; 


            Annotation a = thisMethod.getAnnotation(Annotation.class); 
            a.value1(); //returns 15
            a.value2(); //returns 30
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM