繁体   English   中英

Java注释

[英]Java annotations

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

我是否必须在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

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

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

反射正是查看注释的方式。 它们是附加到类或方法的“元数据”形式,Java注释旨在以这种方式进行检查。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM