@Data
@AllArgsConstructor
@NoArgsConstructor
public class SysUser implements Serializable,Cloneable {
private Integer id=1;
private String uname="hzyao";
public static void CloneObject() {
SysUser sysUser3 = new SysUser(5,"clone");
try {
SysUser sysUser5 = (SysUser) sysUser3.clone();
System.out.println(sysUser5.getId()+" _5_ "+sysUser5.getUname());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
测试方法:
import java.io.*;
import java.lang.reflect.Constructor;
public class Test {
public static void main(String[] args) {
SysUser sysUser = new SysUser(1001,"hzyao");
System.out.println(sysUser.getId()+" _1_"+sysUser.getUname());
String forName = "com.yao.objectCreated.SysUser";
Constructor<SysUser> sysUserConstructor;
try {
Class clz = Class.forName(forName);
SysUser sysUser1 = (SysUser) clz.newInstance();
System.out.println(sysUser1.getId()+" _2_"+sysUser1.getUname());
sysUserConstructor = SysUser.class.getConstructor();
SysUser sysUser2 = sysUserConstructor.newInstance();
System.out.println(sysUser2.getId()+" _3_"+sysUser2.getUname());
Serializable();
SysUser.CloneObject();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void Serializable() {
String filePath = "user.txt";
SysUser sysUser = new SysUser(4,"反序列化创建Object");
try {
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(sysUser);
objectOutputStream.flush();
objectOutputStream.close();
FileInputStream fileInputStream = new FileInputStream(filePath);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
SysUser sysUser1 = (SysUser) objectInputStream.readObject();
objectInputStream.close();
System.out.println(sysUser1.getId()+" _4_ "+sysUser1.getUname());
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果:
1001 _1_hzyao
1 _2_hzyao
------------------------
1 _3_hzyao
4 _4_ 反序列化创建Object
5 _5_ clone
|