2009-04-10 40 views
15

我创建了简单的注解在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和以某种方式援引它?

+0

setAccessible。如果您有安全管理器,阵列版本会更快。当你拥有安全管理员的情况下,setAccessible当然是非常危险的。 – 2009-04-10 16:22:53

+0

可怕...看起来你正在实施你自己的版本JPA – basszero 2009-04-10 16:29:48

+0

@basszero:是的你是对的,我必须为我的大学项目做这个,因为我的愚蠢的老师住在山洞里,不允许使用任何图书馆,如Toplink等... – 2009-04-10 17:24:19

回答

11

每个对象都应该有toString()定义。 (你可以覆盖这个每个类来获得更有意义的表示)。

那么,你的“//这里我不知道”的评论是,你可以有:

Object value = field.get(table); 
// gets the value of this field for the instance 'table' 

log += "value: " + value + "\n"; 
// implicitly uses toString for you 
// or will put 'null' if the object is null 
9

反思是正是的方式来解决它。在执行时发现关于类型及其成员的事情几乎是反射的定义!你做的这种方式对我来说看起来很好。

要查找字段的值,使用field.get(table)

4

反思是正好看注解的方式。它们是附加到类或方法的“元数据”的一种形式,并且Java注释被设计为以这种方式进行检查。

2

反射是处理对象的一种方法(可能是唯一的方法,如果字段是私人的,没有任何一种存取方法)。你需要看看Field.setAccessible或者Field.getType

另一种方法是使用compile-time annotation processor来生成另一个用于枚举带注释的字段的类。这需要Java 5中的一个com.sun API,但在Java 6 JDK中(IDE等IDE可能需要特殊的项目配置)支持更好。