har*_*ani 3 java reflection annotations class
我正在编写一个以类实例作为参数的函数。我想获取在类上定义的特定注释的值。班级:
@AllArgConstructor
@MyAnnotation(tableName = "MyTable")
public class MyClass {
String field1;
}
Run Code Online (Sandbox Code Playgroud)
想要检索注释值的函数。
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`
}
}
Run Code Online (Sandbox Code Playgroud)
我的注释:
@DynamoDB
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface MyAnnotation {
/**
* The name of the table to use for this class.
*/
String tableName();
}
Run Code Online (Sandbox Code Playgroud)
函数 getTableName-1 显示编译错误,而 getTableName-2 工作正常。我在这里做错了什么?我想实现类似于 getTableName-1 的功能。
小智 5
您可以通过以下方式访问这些值:
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";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8918 次 |
| 最近记录: |