我已经在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()
的方法,还是有更好的解决方法?基本上,我只需要每个带注释的字段的字符串表示形式。编辑:是的
field.get(table)
可以工作,但仅适用于public
字段,是否有任何方法可以即使对于private
字段也能够做到这一点?还是我必须创建getter并以某种方式调用它?