我正在寫一個函數,它將Class實例作爲參數。我想獲得在一個類上定義的特定註釋的價值。 類別:如何使用Java獲取類級註釋值反映?
@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`
}
}
MyAnnotation:
@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的函數。
請,加@MyAnnotation –
的代碼是什麼,你得到確切的編譯器錯誤消息? – SpaceTrucker
@SpaceTrucker Intellij不允許我做.tableName()。無法解析方法tableName() –