在我的生活中,我创建了许多注释,现在出现了奇怪的情况,我需要这个注释来做,并且认为Java完全不支持它。请有人告诉我我是对是错。
以下是我的注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DetailsField {
public String name();
}现在是问题!我希望名称()函数的缺省值是它自己发布注释的字段的名称。
不知道类加载器是如何处理注释的,我很确定这不是在标准的类加载器中实现的,而是可以通过字节码工具在自定义类加载器加载时实现吗?(我很确定这是否是我唯一能找到的解决办法,只是好奇而已)
有什么想法吗?还是我希望太多了?
发布于 2010-01-03 17:46:44
我认为可以对字节码进行测试(在类加载时)来实现这一功能,但这似乎是一种高度复杂且可能不可移植的解决方案。
解决问题的最佳解决方案是创建一个类,它用名称计算逻辑来装饰注释实例(a-la装饰器设计模式)。
编辑:在接口中添加了name()定义
package p1;
import java.lang.annotation.*;
import java.lang.reflect.*;
public class A {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DetailsField {
public int n1();
public String name() default "";
}
public static class Nameable implements DetailsField {
private final DetailsField df;
private final Field f;
public Nameable(Field f) {
this.f = f;
this.df = f.getAnnotation(DetailsField.class);
}
@Override
public Class<? extends Annotation> annotationType() {
return df.annotationType();
}
@Override
public String toString() {
return df.toString();
}
@Override
public int n1() {
return df.n1();
}
public String name() {
return f.getName();
}
}
public class B {
@DetailsField(n1=3)
public int someField;
}
public static void main(String[] args) throws Exception {
Field f = B.class.getField("someField");
Nameable n = new Nameable(f);
System.out.println(n.name()); // output: "someField"
System.out.println(n.n1()); // output: "3"
}
}https://stackoverflow.com/questions/1995133
复制相似问题