JAVA-如何从注释中获取注释? [英] JAVA - How to get annotations from Annotation?

查看:237
本文介绍了JAVA-如何从注释中获取注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从注释中获取注释,但是奇怪的是我无法从注释实例中获取单个注释.我该如何解决?我想从此注释实例中获取注释.

I want to get annotations from annotation, but the weird thing is I can't get single annotation from annotation instance. How do I solve this? I want to get annotations from this annotation instance.

public static void test(Annotation annotation) {
    System.out.println("ValidBoolean annotation len:" + ValidBoolean.class.getAnnotations().length);
    System.out.println(annotation.getClass().getName() + ":" + annotation.getClass().getAnnotations().length);
    if (annotation instanceof ValidBoolean) {
        ValidBoolean validBoolean = (ValidBoolean) annotation;
        System.out.println("[BOOLEAN]" + validBoolean.getClass().getName() + ":" + validBoolean.getClass().getAnnotations().length);
    }
}

打印结果是:

ValidBoolean annotation len:3
com.sun.proxy.$Proxy28:0
[BOOLEAN]com.sun.proxy.$Proxy28:0

推荐答案

如果我对您的理解正确,那么您想这样做:

If I understand you correctly, you want to do:

Annotation[] annotationAnnotations = annotation.annotationType().getAnnotations();

通常, annotationType() 如此工作

Generally, annotationType() works such that

someClass.getAnnotation(someAnnotationClass).annotationType() == someAnnotationClass

所以annotation instanceof ValidBoolean也暗示annotation.annotationType() == ValidBoolean.class,因此在它们上调用.getAnnotations()将导致相同的注释.

So annotation instanceof ValidBoolean also implies annotation.annotationType() == ValidBoolean.class, thus invoking .getAnnotations() on them will lead to the same annotations.

这篇关于JAVA-如何从注释中获取注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆