Java 将注释属性传递给元注释

Java 将注释属性传递给元注释,java,annotations,Java,Annotations,假设我有一个带有属性的注释: @Named(name = "Steve") private Person person 我想创建一个包含多个元注释的复合注释,包括一个带有属性的注释 @Named @AnotherAnnotation @YetAnotherAnnotation public @interface CompoundAnnotation { ... } 有没有一种方法可以将复合注释的属性传递给其中一个元注释 例如,类似这样的事情: @CompoundAnnotation

假设我有一个带有属性的注释:

@Named(name = "Steve")
private Person person
我想创建一个包含多个元注释的复合注释,包括一个带有属性的注释

@Named
@AnotherAnnotation
@YetAnotherAnnotation
public @interface CompoundAnnotation {

    ...
}
有没有一种方法可以将复合注释的属性传递给其中一个元注释

例如,类似这样的事情:

@CompoundAnnotation(name = "Bob")
private Person person;
这相当于,但比

@Named(name = "Bob")
@AnotherAnnotation
@YetAnotherAnnotation
private Person person;
谢谢

PS为我对示例注释的错误选择表示歉意-我没有考虑javax.inject。@命名注释,只是一些具有属性的任意注释


谢谢大家的回答/评论

这显然是不可能的。然而,碰巧我的案例有一个简单的解决方法,我将与大家分享,以防它对任何人都有帮助:

我正在使用Spring,希望创建自己的注释,将@Component作为元注释,从而通过组件扫描自动检测。但是,我还希望能够设置BeanName属性(对应于@Component中的value属性),这样我就可以拥有自定义的bean名称

事实证明,Spring上那些深思熟虑的人正是这样做的——AnnotationBeanNameGenerator将接受它所传递的任何注释的“value”属性,并将其用作bean名称(当然,默认情况下,它只会获得@Component或将@Component作为元注释传递的注释)。回想起来,我从一开始就很清楚这一点——这就是以@Component作为元注释的现有注释(如@Service和@Registry)如何提供bean名称

希望对某人有用。我仍然认为这是一个遗憾,这是不可能的更普遍的虽然

有没有一种方法可以将复合注释的属性传递给其中一个元注释

我认为简单的答案是“不”。例如,无法询问
Person
上面有什么注释,也无法获得
@命名的

更复杂的答案是,可以链接注释,但必须通过反射来研究这些注释。例如,以下工作:

@Bar
public class Foo {
    public static void main(String[] args) {
        Annotation[] fooAnnotations = Foo.class.getAnnotations();
        assertEquals(1, fooAnnotations.length);
        for (Annotation annotation : fooAnnotations) {
            Annotation[] annotations =
                annotation.annotationType().getAnnotations();
            assertEquals(2, annotations.length);
            assertEquals(Baz.class, annotations[0].annotationType());
        }
    }

    @Baz
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Bar {
    }

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Baz {
    }
}
但是,以下语句将返回null:

// this always returns null
Baz baz = Foo.class.getAnnotation(Baz.class)

这意味着任何正在寻找
@Baz
注释的第三方类都不会看到它。

几年后的现在,由于您使用的是Spring,您现在要求的是使用@AliasFor注释

例如:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringApplicationConfiguration
@ActiveProfiles("test")
public @interface SpringContextTest {

    @AliasFor(annotation = SpringApplicationConfiguration.class, attribute = "classes")
    Class<?>[] value() default {};

    @AliasFor("value")
    Class<?>[] classes() default {};
}
@Retention(RetentionPolicy.RUNTIME)
@目标(ElementType.TYPE)
@Spring应用程序配置
@ActiveProfiles(“测试”)
public@interface SpringContextTest{
@别名(annotation=SpringApplicationConfiguration.class,attribute=“classes”)
类[]值()默认值{};
@别名(“值”)
类[]类()默认值{};
}

现在,您可以使用
@SpringContextTest(MyConfig.class)
对测试进行注释,令人惊讶的是,它实际上是按照您所期望的方式工作的。

我不知道如何操作的,除非您在加载时通过字节码操作添加注释。(或者我想是一个定制的注释处理器。)我很想看看什么是可能的,没有技巧。在这里大声想一想,如果你用另一个注释和YAA注释了一个基类,然后Person类扩展了它,这不是一个解决办法吗?再看看反思,也许你会有一些想法:与