【发布时间】:2021-05-24 12:17:17
【问题描述】:
@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
我该怎么办?
【问题讨论】:
-
如果您收到 500 错误,则服务器端日志应该有异常。你能附上异常堆栈跟踪吗?但我的猜测是您正在使用调用 getValue() 的结果并将其视为一个数组 - 没有 null 检查(getValue 可以返回 null)。也许您想返回一个空数组?
-
一般返回
Object[]不是一个好主意。Field[]会更好,同时为数组或集合返回null几乎总是不是您想要的,使用空数组return new Field[0];会更好 -
@Lino 如果我使用 Field[],则会发生新错误,即类型不匹配:无法从 Stream
转换为 Field[] -
@OndraK。请查找随附的警告
-
@Bhumika 您需要将
toArray()方法更改为toArray(new Field[0])或者当您使用更高版本的java(我认为是Java11)时,您可以使用toArray(Field::new)
标签: java hibernate annotations sts