【问题标题】:merge multiple annotations with parameters将多个注释与参数合并
【发布时间】:2017-04-28 11:53:38
【问题描述】:

我在使用多个注释时遇到了问题,这些注释都或多或少地表达了相同的内容,但针对不同的框架,我想将它们全部组合到一个自定义注释中。目前它看起来像这样:

@Column(name = "bank_account_holder_name")
@XmlElement(name = "bank_account_holder_name")
@SerializedName("bank_account_holder_name")
@ApiModelProperty(name = "bank_account_holder_name", value = "The name of the recipient bank account holder")
public String bankAccountHolderName;

如您所见,它们都重复相同的字符串,我想将它们组合起来,但我还没有找到这样做的方法。

是否有可能做到这一点,还是我必须继续这样做或更改/创建一个新框架?

【问题讨论】:

    标签: java frameworks annotations code-structure


    【解决方案1】:

    答案是:可能不,这是不可能的(使用“标准”java)。

    你看,注释没有inheritance,只有“多重”继承可以让你表达:

    public @interface MultiAnnotiation extends Column, XmlElement, ...
    

    这些注解很可能是这样工作的:在运行时,相应的框架使用反射来检查某个对象是否具有该注解。如果它没有找到“它的”注解,什么也不会发生。

    因此,您需要一种“神奇地”将这些注释插入到类文件中的方法。

    归结为:当您编写自己的编译器并在 java 之上发明一些东西时,您可以做类似的事情。

    处理编译器插件附带的注解(意思是:在编译时处理的注解)时,情况可能会有所不同。也许您可以编写自己的自定义注释,然后触发 same 编译时操作。

    长话短说:所有这些听起来都有趣,而是高级,而且很可能:不会产生健壮的、值得生产的代码!

    【讨论】:

    • 我认为它不会神奇地与以下方式一起工作:@Clumn(name = magic) public @interface CustomInterface ?
    • 这将注释注释。这并不意味着使用 CustomInterface 注释的内容会看到 Column 注释。
    【解决方案2】:

    可以将一些注解合并为一个注解。例如 Spring 在 SpringBootApplication-Annotation 中执行:

    /**
     * Indicates a {@link Configuration configuration} class that declares one or more
     * {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration
     * auto-configuration} and {@link ComponentScan component scanning}. This is a convenience
     * annotation that is equivalent to declaring {@code @Configuration},
     * {@code @EnableAutoConfiguration} and {@code @ComponentScan}.
     *
     * @author Phillip Webb
     * @since 1.2.0
     */
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @Configuration
    @EnableAutoConfiguration
    @ComponentScan
    public @interface SpringBootApplication {
    
        /**
         * Exclude specific auto-configuration classes such that they will never be applied.
         * @return the classes to exclude
         */
        Class<?>[] exclude() default {};
    
    }
    

    但我不知道是否可以从合并的注释中为内部注释设置一个值。

    【讨论】:

    • 问题归根结底:spring 框架是如何做到的……大概是通过知道这个注解的意思;并专门为此做一些事情。
    • @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) 看最后一件事...
    猜你喜欢
    • 2018-04-20
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    相关资源
    最近更新 更多