简体   繁体   English

如何将作为“值”调用注释的类名和方法传递给注释属性

[英]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我不想对“name”属性进行硬编码,而是需要将它作为这样的东西传递。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
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何调用一个类,该类将获得被调用的类的名称? - How can I call a class which will get the name of the class which is being invoked? 是否有一个程序可以告诉您正在调用哪个类/方法 - Is there a program that can tell you which class/method is being invoked 如何获取具有注释的方法名称? - How can I get the method name which has annotation? 如何在Java方法中传递名称值注释? - How to pass name value annotation in Java method? 如何确定正在调用哪个Struts动作? - How can I determine which Struts action is being invoked? 如何确定在运行时调用了哪个类的`main`方法? - How can I determine which class's `main` method was invoked at runtime? 如何使用特定的Annotation获取所有方法的javadoc,方法名称和包/类名? - How can I get the javadoc of all methods with a specific Annotation, with the method name and package/class name? 如何将值传递给没有参数的方法? - How can I pass value to a method which doesnt have parameters? 我想读取标签的属性“名称”的属性值 <Attribute> 在哪个属性“类”存在..我该怎么做? - I want to read attribute value of attribute “name” of Tag <Attribute> in which attribute “class” is present.. how do i do that? 如何检查哪个类调用了方法 - How to check which class invoked a method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM