Java注解 [英] Java annotations

查看:36
本文介绍了Java注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 J​​ava 中创建了简单的注释

I've created simple annotation in 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.但是我在获取每个字段的时遇到了问题,因为它们都是不同的数据类型.

I need to iterate over all fields, that are annotated with Column and get name and value of field and annotation. But I've got problem with getting value of each field, since all of them are of different data type.

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

Is there anything that would return collection of fields that have certain annotation? I managed to do it with this code, but I don't think that reflection is good way to solve it.

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() 这样的方法,还是有更好的方法来解决这个问题?基本上我需要的是每个被注释字段的字符串表示.

Do I have to wrap every field in object, which would implement method like getValue(), or is there some better way around this? Basicly all I need is string representation of each field that is annotated.

edit: 是的 field.get(table) 有效,但仅适用于 public 字段,即使对于 private 有什么方法可以做到这一点代码>字段?还是我必须创建 getter 并以某种方式调用它?

edit: yep field.get(table) works, but only for public fields, is there any way how to do this even for private fields? Or do I have to make getter and somehow invoke it?

推荐答案

每个对象都应该定义 toString().(您可以为每个类覆盖它以获得更有意义的表示).

Every object should has toString() defined. (And you can override this for each class to get a more meaningful representation).

所以你的//这里我不知道"评论在哪里,你可以:

So you where your "// here I don't know" comment is, you could have:

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注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆