dimanche 3 mai 2020

How to read custom annotation value using reflection?

I am trying to read custom annotation value using reflection.

I see the custom annotation in debug but when i try to typecast annotation to my custom annotation, I am getting ClassCastException.

What am I doing wrong?

//custom annotation

@Retention(Retention.RUNTIME)
@Target({ElementType.METHOD})
public @interface SendEmail{
public String id;
}


//method annotated with custom annotation

@SendEmail(id="test@test.com")
public void testEmail(){

}


// extracting custom annotation using reflection

Set<Method> annotatedMethods = reflections.getMethodsAnnotatedWith(SendEmail.class);

for(Methods method : annotatedMethods){
  Annotations[] annotations = method.getDeclaredAnnotations();
  SendEmail sendEmail = method.getAnnotation(SendEmail.class); // returns null;

  for(Annotation annotation : annotations){
    annotation.annotationType.getName(); // com.test.email.annotation.SendEmail
    annotation.toString(); // @com.test.email.annotation.SendEmail(id=test@test.com)
    SendEmail sendEmail = (SendEmail) annotation; // ClassCastException com.sun.proxy.$Proxy24 cannot be cast to com.test.email.annotation.SendEmail

    if(annotation.annotationType.getName() == SendEmail.class.getName()){
      SendEmail sendEmail = (SendEmail) annotation; // ClassCastException com.sun.proxy.$Proxy24 cannot be cast to com.test.email.annotation.SendEmail
    }
  }








Aucun commentaire:

Enregistrer un commentaire