我在 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
吗?还是我必须制作吸气剂并以某种方式调用它?