mardi 10 octobre 2017

How to get class level annotation value using Java reflect?

I am writing a function which takes Class instance as a parameter. I want to get value of a specific annotation defined over a class. Class:

@AllArgConstructor
@MyAnnotation(tableName = "MyTable")
public class MyClass {
    String field1;
}

Function that want to retrieve annotation value.

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`
    }
}

Function getTableName-1 shows me compilation error whereas getTableName-2 works just fine. What am I doing wrong here? I want to implement function similar to getTableName-1.





Aucun commentaire:

Enregistrer un commentaire