考虑以下类(class)。
public class UserDTO {
private String email;
private String password;
private String country;
private String fName;
private String lName;
private String type;
private String profPicPath;
public UserDTO(String fNme, String lNme, String profPic) {
this.setfName(fNme);
this.setlName(lNme);
this.setProfPicPath(profPic);
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfPicPath() {
return profPicPath;
}
public void setProfPicPath(String profPicPath) {
this.profPicPath = profPicPath;
}
我想创建一个只包含 fName、Lname 和 profPicPath 的对象。我创建了一个构造函数来仅初始化这三个字段。但是当我使用这个构造函数创建一个对象时,它包含其他属性以及空值。 Java 中是否有任何方法可以创建仅具有选定属性的对象?
最佳答案
我认为您对域/模型对象和 DTO 对象感到困惑。域/模型类表示完整的属性集,而您指定的 DTO 表示域/模型类中属性的子集,例如User
类是您的域/模型类,表示完整的属性集(电子邮件、密码、国家/地区、fName、lName、类型、性别、国家/地区、profPicPath 等),然后您可以拥有 DTO,例如, UserLoginCredentialDTO
(具有电子邮件和密码属性),UserDemographyDTO
(具有性别、国家等属性)。
除此之外,JB Nizet 和 Abra 的评论非常有效,将帮助您从 Java 的角度更好地理解这个概念。
关于java - 如何创建包含选定属性的 Java 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58361816/