0

我有一个包含多个字段并指定了 JsonView 的实体:

public class Client {

   @JsonView(Views.ClientView.class)
   @Column(name = "clientid")
   private long clientId;

   @JsonView(Views.ClientView.class)
   @Column(name = "name")
   private String name

   @JsonView(Views.SystemView.class)
   @Column(name = "istest")
   private boolean istest;
   .........

}

视图定义如下:

public class Views {

  public interface SystemView extends ClientView {
  }

  public interface ClientView {
  }
}

我还有一个简单的控制器来更新客户端。由于该字段istest设置为SystemView,我不希望客户端更新该字段。

我已经按顺序阅读了帖子,这必须通过首先加载客户端然后相应地更新参数来手动完成(在我的情况下clientIdname)。

现在我想获取需要更新的字段列表(即标记JsonView为的字段Views.ClientView.class)。我尝试了以下方法,但它不起作用:

ObjectReader reader = objectMapper.readerWithView(SystemView.class);
ContextAttributes attributes = reader.getAttributes();

但是,attributes没有任何元素返回。

有没有办法根据视图获取此字段列表?

4

1 回答 1

0

您可以尝试访问和检查类中的字段注释,Reflection如下所示:

List<Field> annotatedFields = new ArrayList<>();
Field[] fields = Client.class.getDeclaredFields();
for (Field field : fields) {
    if (!field.isAnnotationPresent(JsonView.class)) {
        continue;
    }
    JsonView annotation = field.getAnnotation(JsonView.class);
    if (Arrays.asList(annotation.value()).contains(Views.SystemView.class)) {
        annotatedFields.add(field);
    }
}

在上面的示例中,annotatedFields将包含一个类中的字段列表,其中使用值 contains 进行Client注释。JsonViewViews.SystemView.class

于 2016-07-11T16:06:16.067 回答