我创建了简单的注解在Java中Java注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
String columnName();
}
和类
public class Table {
@Column(columnName = "id")
private int colId;
@Column(columnName = "name")
private String colName;
private int noAnnotationHere;
public Table(int colId, String colName, int noAnnotationHere) {
this.colId = colId;
this.colName = colName;
this.noAnnotationHere = noAnnotationHere;
}
}
我需要遍历所有领域,被标注有Column
并得到名和值的字段和注释。但我得到值每个领域的问题,因为他们都是不同的数据类型。
有没有什么会返回具有某些注释的字段的集合? 我设法用这段代码来做,但我不认为这种反射是解决它的好方法。
Table table = new Table(1, "test", 2);
for (Field field : table.getClass().getDeclaredFields()) {
Column col;
// check if field has annotation
if ((col = field.getAnnotation(Column.class)) != null) {
String log = "colname: " + col.columnName() + "\n";
log += "field name: " + field.getName() + "\n\n";
// here i don't know how to get value of field, since all get methods
// are type specific
System.out.println(log);
}
}
我一定要在包装物各个领域,这将实现像getValue()
方法,还是有一些解决这个更好的办法?基本上我需要的是每个被注释的字段的字符串表示。
编辑:yep field.get(table)
作品,但只有public
领域,有没有什么办法如何做到这一点,即使是private
领域?或者我必须让getter和以某种方式援引它?
setAccessible。如果您有安全管理器,阵列版本会更快。当你拥有安全管理员的情况下,setAccessible当然是非常危险的。 – 2009-04-10 16:22:53
可怕...看起来你正在实施你自己的版本JPA – basszero 2009-04-10 16:29:48
@basszero:是的你是对的,我必须为我的大学项目做这个,因为我的愚蠢的老师住在山洞里,不允许使用任何图书馆,如Toplink等... – 2009-04-10 17:24:19