我创建了一个简单的注释类:
@Retention(RUNTIME)
public @interface Column {
public String name();
}
我在像这样的类中使用它:
public class FgnPzt extends Point {
public static final String COLUMN_TYPE = "type";
@Column(name=COLUMN_TYPE)
protected String type;
}
我知道我可以迭代声明的字段并获取这样的注释:
for (Field field : current.getDeclaredFields()) {
try {
Column c = field.getAnnotation(Column.class);
[...]
} catch(Exception e) {
[...]
}
}
如何直接通过带注释的名称获取字段type
而不迭代类的声明字段?
答案 0 :(得分:3)
如果您需要进行多次访问,可以预先处理注释。
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);
}
}