Java 建立物件的四種方式
阿新 • • 發佈:2018-11-20
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);