向 Java 类添加编程注释 [英] Adding programmatic annotations to a Java class
问题描述
使用示例:
我想在类字段上添加自定义注释 @MyContainer,然后在所有这些字段上自动添加相关的 Hibernate 注释(取决于字段类型和属性).
此外,我需要向类添加 JAXB XmlType 注释,并将类型名称基于类名称.
我还想根据他们的类型等向字段添加注释.所有添加的注释都应该在运行时可用(因此休眠/JAXB 可以找到它们).
我知道以下选项:
Usage example:
I want to put on class fields a custom annotation @MyContainer and then add automatically on all such fields relevant Hibernate annotations (depending on field type and properties).
In additional I need to add JAXB XmlType annotation to the class and base the type name on the class name.
I would want additionally to add annotations to fields based on thier types, etc.
All added annotations should be available at run time (So hibernate / JAXB can find them).
I'm aware of the following options:
- 预处理类源(错误选项)
- 在编译期间使用 javax.annotation.processing API 进行处理
- 使用 Java Assist 等工具进行编译后操作
- 在类加载期间使用 java.lang.instrument API 进行操作
- 用 AspectJ 来做(不够强大)
我的主要目标是:
- 保持类和源之间的同步以进行调试
- 支持从 Maven 和 IDE (Eclipse/Intellij) 工作
如果已经做过此类事情的人能够推荐用于此类任务的最佳方法(可能还有潜在的陷阱),我将不胜感激.
I'll appreciate if people who already done such things can recommend the best approach for such a task (and perhaps potential pitfalls).
推荐答案
这里是定义自定义注解的代码示例.这个@TesterInfo 应用于类级别,存储测试人员的详细信息.这显示了返回类型的不同用法——枚举、数组和字符串.
Here is a code example for defining custom annotation. This @TesterInfo is applied on class level, store the tester details. This shows the different use of return types – enum, array and string.
package com.mkyong.test.core;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) //on class level
public @interface TesterInfo {
public enum Priority {
LOW, MEDIUM, HIGH
}
Priority priority() default Priority.MEDIUM;
String[] tags() default "";
String createdBy() default "Mkyong";
String lastModified() default "03/01/2014";
}
这篇关于向 Java 类添加编程注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!