Как прочитать пользовательское значение аннотации, используя отражение? - PullRequest
0 голосов
/ 04 мая 2020

Я пытаюсь прочитать значение пользовательской аннотации с помощью отражения.

Я вижу пользовательскую аннотацию в отладке, но когда я пытаюсь типизировать аннотацию к моей пользовательской аннотации, я получаю ClassCastException.

Что я делаю не так?

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




Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...