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.
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With