java获得实例对象的几种方法

// 1.new
Dog d1 = new Dog();
d1.say();
// 2.Class.forName
Dog d2 = (Dog) Class.forName("com.test.Dog").newInstance();
d2.say();
// 3.ClassLoader
ClassLoader c = ClassLoader.getSystemClassLoader();
Class classT = c.loadClass("com.test.Dog");
Dog d = (Dog) classT.newInstance();
d.say();
// 4.对象流
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("D:/tmp.txt"));
// 序列化对象
Student stuo = new Student("11", "张三");
out.writeObject(stuo);
out.close();
// 反序列化对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"D:/tmp.txt"));
Student stuI = (Student) in.readObject();
System.out.println("id:" + stuI.getId());
System.out.println("姓名:" + stuI.getName());
in.close();
class Student implements Serializable {
private static final long serialVersionUID = 1L;// 序列号
private String id;// 学号
private String name;// 姓名

public Student() {
}

public Student(String id, String name) {
this.id = id;
this.name = name;
}

你可能感兴趣的:(java)