我正在编写一个以类实例作为参数的函数。我想获取在类上定义的特定注释的值。 类(class):
@AllArgConstructor
@MyAnnotation(tableName = "MyTable")
public class MyClass {
String field1;
}
想要检索注释值的函数。
public class AnnotationValueGetter{
public String getTableName-1(Class reflectClass){
if(reflectClass.getAnnotation(MyAnnotation.class)!=null){
return reflectClass.getAnnotation(MyAnnotation.class).tableName();
//This does not work. I am not allowed to do .tableName(). Java compilation error
}
}
public String getTableName-2{
Class reflectClass = MyClass.class;
return reflectClass.getAnnotation(MyAnnotation.class).tableName()
//This works fine.`enter code here`
}
}
我的注释:
@DynamoDB
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface MyAnnotation {
/**
* The name of the table to use for this class.
*/
String tableName();
}
函数 getTableName-1 显示编译错误,而 getTableName-2 工作正常。我在这里做错了什么?我想实现类似getTableName-1的功能。
最佳答案
您可以通过以下方式访问值:
public class AnnotationValueGetter {
public String getTableName1(Class reflectClass) {
if (reflectClass.isAnnotationPresent(MyAnnotation.class)) {
Annotation a = reflectClass.getAnnotation(MyAnnotation.class);
MyAnnotation annotation = (MyAnnotation) a;
return annotation.tableName();
}
return "not found";
}
}
关于java - 如何使用Java Reflect获取类级别注释值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46661781/