基于此问题 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
答案 0 :(得分:2)
您可以这样做。您需要根据需要在过滤器中添加更多条件:
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);
答案 1 :(得分:0)
您可以使用“反射”库。
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());
});