mun*_*ger 9 java frameworks annotations code-structure
我在使用多个注释时遇到问题,这些注释或多或少都说相同的事情,但针对不同的框架,我想将它们全部归为一个自定义注释。目前它看起来像这样:
@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;
Run Code Online (Sandbox Code Playgroud)
如您所见,它们都重复相同的字符串,我想将它们组合起来,但我还没有找到这样做的方法。
是否有可能做到这一点,或者我是否必须继续这样做或更改/创建一个新框架?
可以将一些注释合并为仅一个注释。例如,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 {};
}
Run Code Online (Sandbox Code Playgroud)
但我不知道是否可以从合并的注释中为内部注释设置一个值。
答案是:可能不,这是不可能的(使用“标准”java)。
你看,注解没有继承,只有“多重”继承可以让你表达:
public @interface MultiAnnotiation extends Column, XmlElement, ...
Run Code Online (Sandbox Code Playgroud)
最有可能的是,这些注解是这样工作的:在运行时,相应的框架使用反射来检查某个对象是否具有该注解。如果它没有找到“它的”注释,则什么也不会发生。
所以你需要一种方法来“神奇地”将这些注释插入到你的类文件中。
归结为:当您编写自己的编译器并在 Java 之上发明一些东西时,您就可以做类似的事情。
处理编译器插件附带的注释(意思是:在编译时处理的注释)时,情况可能会有所不同。也许您可以编写自己的自定义注释,然后触发相同的编译时操作。
长话短说:所有这些听起来很有趣,但相当先进,而且很可能:不会产生健壮的、值得生产的代码!
| 归档时间: |
|
| 查看次数: |
9532 次 |
| 最近记录: |