查找包含任何注释的文件的名称


@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

我该怎么办?

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

最新更新