gpt4 book ai didi

java - 如何在多个变量上应用单个注释?

转载 作者:行者123 更新时间:2023-11-30 09:04:21 26 4
gpt4 key购买 nike

我是 Java Annotation 的菜鸟,一直在寻找同时在多个变量上应用单个 annotation 的方法。

代码:

@Document(collection = "users")
public class User {

private ObjectId id;

@NotNull
private String email;
private String imageURL;
private String authToken;

private Date createdDate;
private Date updateDate;
private boolean isActivated;
private int credits;

.....getter/Setter Method

我也想在 emailimageURLauthToken 上应用 @NotNull 属性。我可以通过将 @NotNull 写入每个 variable 来做到这一点,但不是首选。怎么做?

最佳答案

@NotNull 注释可以应用于元素而不是元素组。

JavaDoc: The annotated element must not be null. Accepts any type.

如果你真的想摆脱样板代码,你可以使用像 Lombok 这样的框架,它可以在一定程度上帮助你。

链接:http://projectlombok.org/features/Data.html

或者您可以使用反射来验证所有方法。

for (Field f : obj.getClass().getDeclaredFields()) {
f.setAccessible(true); // optional
if (f.get(obj) == null) {
f.set(obj, getDefaultValueForType(f.getType()));
// OR throw error
}
}

关于java - 如何在多个变量上应用单个注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25261236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com