2017-10-10 60 views
0

我正在寫一個函數,它將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的函數。

+0

請,加@MyAnnotation –

+0

的代碼是什麼,你得到確切的編譯器錯誤消息? – SpaceTrucker

+0

@SpaceTrucker Intellij不允許我做.tableName()。無法解析方法tableName() –

回答

0

使用類與泛型類型參數:

public String getTableName-1(Class<?> reflectClass){ 
     //Your code here. 
} 

還有一建議, 它能夠更好地使用reflectClass.isAnnotationPresent(MyAnnotation.class)代替reflectClass.getAnnotation(MyAnnotation.class)!=null在if塊的條件。

+0

感謝您的這一點。已經將其納入我的代碼。 –

0

您可以訪問這些值是這樣的:

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