2017-10-10 10 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:getTableName-2だけで正常に動作し、一方、

@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-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を使用します。

+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"; 
    } 
} 
関連する問題