【问题标题】:Reflection Java - Get all fields of all declared class反射 Java - 获取所有声明类的所有字段
【发布时间】:2018-07-27 17:09:50
【问题描述】:
基于这个问题
Get all Fields of class hierarchy
我有一个类似的问题:
我有 A 类和 B 类:
class A {
@SomeAnnotation
long field1;
B field2; //how can i access field of this class?
}
class B {
@SomeAnnotation
long field3;
}
我想从这 2 个类中获取所有带有注释 @SomeAnnotation 的字段值。
喜欢:
A.field1
B.field3
【问题讨论】:
标签:
java
reflection
recursive-datastructures
【解决方案1】:
你可以这样做。您需要根据您的要求在过滤器中添加更多条件:
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
fields.addAll(
Arrays.stream(type.getDeclaredFields())
.filter(field -> field.isAnnotationPresent(NotNull.class))
.collect(Collectors.toList())
);
if (type.getSuperclass() != null) {
getAllFields(fields, type.getSuperclass());
}
return fields;
}
调用示例:
List<Field> fieldList = new ArrayList<>();
getAllFields(fieldList,B.class);
【解决方案2】:
您可以使用“反射”库。
https://github.com/ronmamo/reflections
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("your.packageName"))
.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner(), new FieldAnnotationsScanner()));
Set<Field> fields =
reflections.getFieldsAnnotatedWith(YourAnnotation.class);
fields.stream().forEach(field -> {
System.out.println(field.getDeclaringClass());
System.out.println(field.getName());
});