1.常量类
class Constant01 {
/**
* @ConstantAnnotation:自定义注解
*/
@ConstantAnnotation("aaa")
public static final String ODD_SCAN = "1";
@ConstantAnnotation("bb")
public static final String BATCH_SCAN = "2";
}
2.自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@interface ConstantAnnotation {
String value() default "";
}
3.根据注解值获取常量值
private static String constant01(String name) {
Field[] fields = Constant01.class.getDeclaredFields();
for (Field f : fields) {
if (name.equals(f.getAnnotation(ConstantAnnotation.class).value())) {
try {
return (String) f.get(f.getName());
} catch (IllegalAccessException e) {
return "未知";
}
}
}
return "未知";
}