Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class level annotation value using Java reflect? [duplicate]

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

MyAnnotation:

@DynamoDB
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface MyAnnotation {

    /**
     * The name of the table to use for this class.
     */
    String tableName();

}

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.

like image 594
harshit modani Avatar asked Oct 11 '25 07:10

harshit modani


1 Answers

you can access the values this way:

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";
  }
}
like image 157
Kai Avatar answered Oct 13 '25 21:10

Kai