Java注释

Jak*_*old 15 java annotations

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
    String columnName();
}
Run Code Online (Sandbox Code Playgroud)

和班级

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;
    }  
}
Run Code Online (Sandbox Code Playgroud)

我需要遍历所有字段,这些字段用注释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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

ken*_*418 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
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 9

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

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