Java注释

我在Java中创建了简单的注释

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Column { String columnName(); } 

和class级

 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注释并获取字段和注释的名称 。 但是我在获取每个字段的时遇到了问题,因为它们都是不同的数据类型

是否有任何东西可以返回具有特定注释的字段集合? 我设法用这个代码做了,但我不认为reflection是解决它的好方法。

 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); } } 

我是否必须在object中包装每个字段,这将实现getValue()类的方法,或者有更好的解决方法吗? 基本上我需要的是每个注释字段的字符串表示。

编辑: field.get(table)有效,但仅适用于public领域,有没有办法如何为private字段做到这一点? 或者我必须制作吸气剂并以某种方式调用它?

每个对象都应该定义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 

反思正是解决问题的方法。 在执行时找出关于类型及其成员的事情几乎就是reflection的定义! 你做的方式看起来很好。

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

reflection正是查看注释的方式。 它们是附加到类或方法的“元数据”forms,Java注释被设计为以这种方式进行检查。

reflection是处理对象的一种方式(如果字段是私有的并且没有任何类型的存取方法,则可能是唯一的方法)。 您需要查看Field.setAccessible和Field.getType 。

另一种方法是使用编译时注释处理器生成另一个用于枚举带注释字段的类。 这需要Java 5中的com.sun API,但在Java 6 JDK中支持更好(像Eclipse这样的IDE可能需要特殊的项目配置)。