java - 在另一个类中重用字段
问题描述
我有两个类似于这些的 POJO:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User {
@SerializedName("name")
@Expose
private String name;
@SerializedName("mail")
@Expose
private String mail;
....
}
public class Profile {
@SerializedName("birthday")
@Expose
private String birthday;
@SerializedName("biography")
@Expose
private String biography;
.....
}
现在我需要第三个 POJO 重用他们的一些字段:
public class RegisterInfo {
@SerializedName("name")
@Expose
private String name;
@SerializedName("birthday")
@Expose
private String birthday;
}
我不想在我的 RegisterInfo 类中复制代码。因此,如果修改“姓名”或“生日”字段,我只需要在一个类中触摸代码即可。那么...有没有办法从我的 RegisterInfo 类中对“姓名”和“生日”字段进行“引用”?
解决方案
您可以对字段使用相同的常量,但重复声明。这样,如果 json 键发生变化,您可以轻松地一次更改所有键。您可以对常量进行静态导入,以使代码看起来像下面这样整洁。
Class JsonConstants {
final static String JSON_NAME = "name"
final static String JSON_MAIL = "mail"
final static String JSON_BIRTHDAY = "birthday"
final static String JSON_BIOGRAPHY = "biography"
}
public class User {
@SerializedName(JSON_NAME)
@Expose
private String name;
@SerializedName(JSON_MAIL)
@Expose
private String mail;
....
}
public class Profile {
@SerializedName(JSON_BIRTHDAY)
@Expose
private String birthday;
@SerializedName(JSON_BIOGRAPHY)
@Expose
private String biography;
.....
}
public class RegisterInfo {
@SerializedName(JSON_NAME)
@Expose
private String name;
@SerializedName(JSON_BIRTHDAY)
@Expose
private String birthday;
}
推荐阅读
- r - R - 按组的最大值在序列中插入缺失的数字
- ibm-cloud - IBM Watson Assistant:如何训练聊天机器人选择正确的意图?
- javascript - JavaScript中的Caesars Cipher - 为什么'A'在这里变成'['?
- android - 如何根据视频大小限制 Seek Bar?
- ios - 非可选字符串自动更改为可选
- mysql - 如何创建文章表、分类和标签?
- r - 如何使用 dplyr 删除所有列中具有 NA 的行?
- java - 在 Jboss Wildfly 上部署 EAR 文件失败
- json - 你如何解析这个 JSON 数据?
- c# - 在 Asp.Net Core 和 Razor 视图中显示来自路径的图像?