版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010739551/article/details/85061117
实现
package com.mikamo.newclass;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = -2237531491283515012L;
private String name;
public Employee() {
}
public Employee(String name) {
this.name = name;
}
public void show(){
if(name != null){
System.out.println(name);
}else{
System.out.println("employee");
}
}
@Override
protected Employee clone() throws CloneNotSupportedException {
return this;
}
}
package com.mikamo.newclass;
import java.io.*;
import java.lang.reflect.Constructor;
public class Test {
public static void main(String[] args){
try {
//使用new关键字构造
Employee e1 = new Employee();
e1.show();
System.out.println("------------------------------------------");
//只能通过无参构成方法构造
Employee e2 = Employee.class.newInstance();
e2.show();
System.out.println("------------------------------------------");
//获取指定的构成方法
Constructor<Employee> constructor = Employee.class.getConstructor(String.class);
Employee e3 = constructor.newInstance("luke");
e3.show();
System.out.println("------------------------------------------");
//通过实现clone方法克隆对象
Employee e4 = e3.clone();
e4.show();
System.out.println("------------------------------------------");
//通过序列化对象写入到文件,和反序列化读取对象
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("D:/employee.txt")));
oo.writeObject(e1);
oo.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("D:/employee.txt")));
Employee e5 = (Employee)ois.readObject();
ois.close();
e5.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果
employee
------------------------------------------
employee
------------------------------------------
luke
------------------------------------------
luke
------------------------------------------
employee
参考
https://mp.weixin.qq.com/s/3u7dTh-TLA8fVlRvfw9BaA