如何通过其注释获取类的字段 [英] How to get field of a class by its annotation

查看:167
本文介绍了如何通过其注释获取类的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的注释类:

I created a simple annotation class:

@Retention(RUNTIME)
public @interface Column {
    public String name();
}

我在诸如此类的某些类中使用它:

I use it in some classes like this:

public class FgnPzt extends Point {

    public static final String COLUMN_TYPE = "type";
    @Column(name=COLUMN_TYPE)
    protected String type;

}

我知道我可以遍历声明的字段并获得如下注释:

I know that I can iterate over the declared fields and obtain the annotation like this:

for (Field field : current.getDeclaredFields()) {
    try {
        Column c = field.getAnnotation(Column.class);
        [...]
    } catch(Exception e) {
        [...]
    }
}

如何直接通过带注释的名称获取字段type,而无需遍历该类的声明字段?

How can I obtain the field type directly by its annotated name without iterating over declared fields of the class?

推荐答案

如果您需要进行多次访问,则可以预处理注释.

If you need to make multiple accesses you can pre-process the annotations.

public class ColumnExtracter<T> {
    private final Map<String, Field> fieldsByColumn;

    public ColumnExtracter(Class<T> clazz) {
        this.fieldsByColumn = Stream.of(clazz.getDeclaredFields())
              .filter(field -> field.isAnnotationPresent(Column.class))
              .collect(Collectors.toMap(field -> field.getAnnotation(Column.class).name(), Function.identity()));
    }

    public Field getColumnField(String columnName) {
        return fieldsByColumn.get(columnName);
    }

    public <R> R extract(String columnName, T t, Class<R> clazz) throws IllegalAccessException {
        return clazz.cast(extract(columnName, t));
    }

    public Object extract(String columnName, T t) throws IllegalAccessException {
        return getColumnField(columnName).get(t);
    }
}

这篇关于如何通过其注释获取类的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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