1.实例化对象赋值
(1)构造函数重载
public class MyTestBean { private long age; private String name; public MyTestBean() { } public MyTestBean(long age, String name) { this.age = age; this.name = name; } public MyTestBean(String name) { this.name = name; } public MyTestBean(long age) { this.age = age; } }
(2)get、set方法
public class MyTestBean { private long age; private String name; public long getAge() { return age; } public void setAge(long age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
2.builder 模式
public class MyTestBean { private final int id; private final String name; private final int type; private final float price; private MyTestBean(Builder builder) { this.id = builder.id; this.name = builder.name; this.type = builder.type; this.price = builder.price; } public static class Builder { private int id; private String name; private int type; private float price; public Builder id(int id) { this.id = id; return this; } public Builder name(String name) { this.name = name; return this; } public Builder type(int type) { this.type = type; return this; } public Builder price(float price) { this.price = price; return this; } public MyTestBean build() { return new MyTestBean(this); } } }
调用:
MyTestBean myTestBean = new MyTestBean.Builder().id(1).name("xq").build();