Чтобы узнать названия полей, в которых есть аннотации

      @Entity
class Student{
 @NotNull
 private int sid;
 @NotNull
 private String sname;
 private int age;
}

я должен показать имя поля, содержащего аннотацию @NotNull

Я создал функцию

      public boolean hasNotNull() {
        return Arrays.stream(this.getClass().getDeclaredFields())
                .anyMatch(field -> field.isAnnotationPresent(NotNull.class));
    }

public Object[] getValue() {
        if (hasNotNull())

            return Arrays.stream(this.getClass().getDeclaredFields())
                    .filter(field -> field.isAnnotationPresent(NotNull.class)).toArray();

        else
            return null;
    }

Но я получаю 500 Internal Server Error.

Ниже приведены предупреждения:

      WARNING: An illegal reflective access operation has occurred
WARNING: Please consider reporting this to the maintainers of com.fasterxml.jackson.databind.util.ClassUtil
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

Что я должен делать?

2 ответа

      public List<String> getValue() {

        if (hasNotNull()) {
            Stream<Field> filter = Arrays.stream(this.getClass().getDeclaredFields())
                    .filter(field -> field.isAnnotationPresent(NotNull.class));
            return filter.map(obj -> obj.getName()).collect(Collectors.toList());
        }

        else
            return null;
    }

Поскольку вы получаете объявленные поля, вы работаете с частными полями, к которым обычно не можете получить доступ. Используйте .setAccessible в поле перед вызовом другого метода для него

Другие вопросы по тегам