0
@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 内部服务器错误。

以下是警告:

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

我应该怎么办?

4

2 回答 2

0
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;
    }
于 2021-02-23T07:36:05.097 回答
-1

由于您获得了声明的字段,因此您可以使用通常无法访问的私有字段。使用 .setAccessible 在字段上调用另一个方法之前

于 2021-02-22T09:07:31.340 回答