生成自定义Java对象的多个元组或字符串组合可以通过以下几种方式实现:
public class CustomObject {
private String name;
private int age;
public CustomObject(String name, int age) {
this.name = name;
this.age = age;
}
}
// 创建对象
CustomObject obj1 = new CustomObject("John", 25);
CustomObject obj2 = new CustomObject("Alice", 30);
public class CustomObject {
private String name;
private int age;
private CustomObject() {}
public static class Builder {
private CustomObject obj;
public Builder() {
obj = new CustomObject();
}
public Builder setName(String name) {
obj.name = name;
return this;
}
public Builder setAge(int age) {
obj.age = age;
return this;
}
public CustomObject build() {
return obj;
}
}
}
// 创建对象
CustomObject obj1 = new CustomObject.Builder()
.setName("John")
.setAge(25)
.build();
CustomObject obj2 = new CustomObject.Builder()
.setName("Alice")
.setAge(30)
.build();
public class CustomObjectFactory {
public static CustomObject createObjectWithName(String name) {
CustomObject obj = new CustomObject();
obj.setName(name);
return obj;
}
public static CustomObject createObjectWithAge(int age) {
CustomObject obj = new CustomObject();
obj.setAge(age);
return obj;
}
}
// 创建对象
CustomObject obj1 = CustomObjectFactory.createObjectWithName("John");
CustomObject obj2 = CustomObjectFactory.createObjectWithAge(25);
以上是生成自定义Java对象的多个元组或字符串组合的几种常见方式。根据具体的需求和场景选择合适的方式来生成对象。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云