我有一个实体,其中包含许多字段并指定了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
,我不希望客户端更新该字段。
我已经在订单帖子中读到,这必须通过首先加载客户端而不是相应地更新参数(在我的情况下是clientId
和name
)来手动完成。
现在我想获取需要更新的字段列表(即标记为JsonView
的字段Views.ClientView.class
)。我已经尝试了以下方法,但它不起作用:
ObjectReader reader = objectMapper.readerWithView(SystemView.class);
ContextAttributes attributes = reader.getAttributes();
但是,attributes
返回时没有任何元素。
有没有办法根据视图获取此字段列表?
您可以尝试访问和检查类中字段的注释,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
将包含类中的字段列表Client
该类中带有值包含 Views.SystemView.class
的 JsonView
注释。