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

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

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 并以某种方式调用它?

最佳答案

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

关于Java注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/738065/

相关文章:

java - 如何禁用推送通知的声音?

java - Spring ajax 400(错误请求)

java - 更新折线图中的值

java - 如何在IntelliJ IDEa中添加@Contract注解?

java - POJO 生成器中的 Android Studio 错误

java - GZIPOutputStream 在单独的线程中进行压缩

java - 从dom列表到xml文件的xml解析

java - 获取项目中的所有注释?

ios - 更改pincolor后注释标题无法显示

java - 如何基于使用批注在REST中创建资源的用户授权特定资源