java中创建对象的5种方式

时间:2022-08-30 17:33:39

java中创建对象的5种方式



复习复习java,准备换工作了~。

上代码


User实体类

/**   
* @Title: User.java
* @date: 2017年8月7日 上午10:25:41
* @version: V1.0
*/
package com.witc.base;

import java.io.Serializable;
import java.util.Date;

/**
* @ClassName: User
* @Description: TODO
* @date: 2017年8月7日 上午10:25:41
*/
public class User implements Cloneable,Serializable{

private static final long serialVersionUID = 1050073612263237216L;

private Date createTime;

@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}

public User(Date createTime) {
super();
this.createTime = createTime;
}


public User() {
super();
}

/**
* @return the createTime
*/
public Date getCreateTime() {
return createTime;
}

/**
* @param createTime the createTime to set
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}

}



public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, FileNotFoundException, IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//1.通过new关键字新建对象,调用构造方法
User user1 = new User();
user1.setCreateTime(new Date());
System.out.println("user1 createTime:"+sdf.format(user1.getCreateTime()));


//2.使用Class类的newInstance方法,调用构造方法
User user2 = (User) Class.forName("com.witc.base.User").newInstance();
user2.setCreateTime(new Date());
System.out.println("user2 createTime:"+sdf.format(user2.getCreateTime()));

//3.使用Constructor类的newInstance方法,调用构造方法
User user3 = User.class.newInstance();
user3.setCreateTime(new Date());
System.out.println("user3 createTime:"+sdf.format(user3.getCreateTime()));

//4.使用clone方法,需要实现Cloneable接口
User user = new User(new Date());
User user4 = (User)user.clone();
System.out.println("user4 createTime:"+sdf.format(user4.getCreateTime()));

//5.使用反序列化,需要实现Serializable接口
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:/Users/Administrator/Desktop/User.txt"));
out.writeObject(user4);
out.close();

ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:/Users/Administrator/Desktop/User.txt"));
User user5 = (User) in.readObject();
in.close();
user5.setCreateTime(new Date());
System.out.println("user5 createTime:"+sdf.format(user4.getCreateTime()));

}


运行效果

java中创建对象的5种方式