【问题标题】:To find out the names of the filed that contain any annotation找出包含任何注释的文件的名称
【发布时间】: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


【解决方案1】:
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;
    }

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      相关资源
      最近更新 更多