gpt4 book ai didi

java - 如何将调用注释的类名和方法作为 "value"传递给注释属性

转载 作者:行者123 更新时间:2023-12-01 18:01:33 25 4
gpt4 key购买 nike

 public class Demo {

public Demo(){}

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

}

}

我不想硬编码“name”属性,而是需要将其传递为类似 this.getClass().getName().NAME_OF_THE_METHOD_ON_WHICH_INVOKED

最佳答案

首先,创建自定义注释

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

然后使用它

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
}
}

关于java - 如何将调用注释的类名和方法作为 "value"传递给注释属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60618811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com