Java 创建对象的四种方式

Java 创建对象的四种方式

1、使用new关键值创建对象

        User user = new user();
        user.setName("小明");
        user.setPass("123456");
        System.out.println(user );

2、使用clone

        User user= new User ();
        Object clone = user.clone();
        System.out.println(clone);
详细的clone (可以克隆之前的对象,之前对象需要实现接口Cloneable)
public class CloneTest {

    public static void main(String[] args) {
        try {
            cloneTest();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
    static void cloneTest() throws CloneNotSupportedException {
        User user = new User();
        user.setPassWord("123456789");
        user.setUserName("小明");
        User cloneUser = (User) user.clone();
        cloneUser.setYearold(18);
        System.out.println(cloneUser.toString());

    }


}
class User implements Cloneable{
    private String userName;
    private String passWord;
    private Integer yearold;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public Integer getYearold() {
        return yearold;
    }
    public void setYearold(Integer yearold) {
        this.yearold = yearold;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    @Override
    public String toString() {
        return "User [userName=" + userName + ", passWord=" + passWord + ", yearold=" + yearold + "]";
    }
}
运行结果
User [userName=小明, passWord=123456789, yearold=18]

3、使用反射

        Class c = Class.forName("com.xxx.User");
        Object o = c.newInstance();
        System.out.println(o);

4、反序列化

        // 先序列化
        User user= new User();
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("user.obj"));
        os.writeObject(user);
        // 再反序列化
        ObjectInputStream is = new ObjectInputStream(new FileInputStream("user.obj"));
        Object o = is.readObject();
        System.out.println(o);

你可能感兴趣的:(Java)