【问题标题】:Pass argument to java annotations将参数传递给 java 注释
【发布时间】:2021-11-10 11:32:38
【问题描述】:

我正在将多个注释组合成一个自定义注释。

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Annotation1(input = SomeClass.class)
@Annotation2(input = SomeClass.class)
@Annotation3(input = SomeClass.class)
public @interface CustomAnnotation {
}

我可以将 SomeClass.class 作为 CustomAnnotation 的输入参数并使其通用吗? 所以我可以在下面这样的地方使用它

@CustomAnnotation(input=SomeClass.class)

【问题讨论】:

    标签: java annotations


    【解决方案1】:

    我可以将 SomeClass.class 作为 CustomAnnotation 的输入参数并使其通用吗?

    是的,你可以。这是来自Spring 框架的@Import 注释的example

    你这样使用它...

    @SpringBootTest
    @Import(other.namespace.Foo.class) // class name specified here
    class SpringBootImportTest {
    

    它的implemented 像这样...

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Import {
    
        /**
         * {@link Configuration @Configuration}, {@link ImportSelector},
         * {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
         */
        Class<?>[] value();
    }
    

    有关创建自定义注释的更多详细信息,请查看this

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多