2

based on this question Get all Fields of class hierarchy

I have a similar question:

i have class A and B:

class A {
  @SomeAnnotation
  long field1;

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

}


class B {

  @SomeAnnotation
  long field3;

}

I want to get all fields values that have the annotation @SomeAnnotation from this 2 class.

like:

A.field1

B.field3

André Ribeiro
  • 77
  • 2
  • 10

2 Answers2

2

You can do it like this. You need to add more condition as per your requirement in filter:

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;
}

Call example:

List<Field> fieldList = new ArrayList<>();
getAllFields(fieldList,B.class);
GolamMazid Sajib
  • 8,698
  • 6
  • 21
  • 39
0

You can use the "reflections" library.

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());
    });
Emre Savcı
  • 3,034
  • 2
  • 16
  • 25