反射Java-获取所有声明类的所有字段

反射Java-获取所有声明类的所有字段,java,reflection,recursive-datastructures,Java,Reflection,Recursive Datastructures,基于这个问题, 我有一个类似的问题: 我有甲级和乙级: class A { @SomeAnnotation long field1; B field2; //how can i access field of this class? } class B { @SomeAnnotation long field3; } 我想从这个2类中获取所有具有注释@SomeAnnotation的字段值 比如: A.1 你可以这样做。您需要根据过滤器中的要求添加更多条件: p

基于这个问题,

我有一个类似的问题:

我有甲级和乙级:

class A {
  @SomeAnnotation
  long field1;

  B field2; //how can i access field of this class?

}


class B {

  @SomeAnnotation
  long field3;

}
我想从这个2类中获取所有具有注释@SomeAnnotation的字段值

比如:

A.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;
}
公共静态列表getAllFields(列表字段,类类型){
fields.addAll(
Arrays.stream(type.getDeclaredFields())
.filter(字段->字段.isAnnotationPresent(NotNull.class))
.collect(收集器.toList())
);
if(type.getSuperclass()!=null){
getAllFields(字段,类型.getSuperclass());
}
返回字段;
}
呼叫示例:

List<Field> fieldList = new ArrayList<>();
getAllFields(fieldList,B.class);
List fieldList=new ArrayList();
getAllFields(字段列表,B.class);
您可以使用“反射”库

反射=新反射(
新的ConfigurationBuilder()
.setURL(ClasspathHelper.forPackage(“您的.packageName”))
.setScanners(新子类扫描程序()、新类型注释扫描程序()、新字段注释扫描程序());
设置字段=
reflections.getFieldsAnnotatedWith(YourAnnotation.class);
fields.stream().forEach(字段->{
System.out.println(field.getDeclaringClass());
System.out.println(field.getName());
});
    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());
    });