java - 如何使用Java Reflect获取类级别注释值?

标签 java class reflection annotations

我正在编写一个以类实例作为参数的函数。我想获取在类上定义的特定注释的值。 类(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/

相关文章:

java - JPA实体和DTO属于Service层还是Spring Repository层

java - 从 Java 连接 PHP 时出现 IllegalStateException

html - 将 iframe 从正文顶部拉伸(stretch)到页面底部

java - Java EE/Jakarta EE 是否支持 Java 模块系统?是否可以使用 Java 模块系统制作 Web 应用程序?

java - 如何检查当前用户是否在 Firebase (Android Java) 上经过身份验证

java - OutOfMemoryError 异常 : Java heap space, 如何调试...?

r - <- R 中的调用类

c# - 命名空间 c# 中的方法

Java - 从接口(interface)到实现的动态类转换

java - 如何从 jar 加载方法而不加载类?