实例化类有四种方式:
1)使用new操作符
2)调用Class对象的newInstance()方法
3)调用clone()方法,对现有实例的拷贝
4)通过ObjectInputStream的readObject()方法反序列化类
1.new操作符
A a1 = new A(); System.out.println("a1: " + a1);
2.Class.forName()的newInstance方法和Constructor对象的newInstance()方法
Class<A> clazz = (Class<A>) Class.forName("com.bjsxt.singleton.A"); Constructor<A> c = clazz.getDeclaredConstructor(null); A a2 = c.newInstance(); System.out.println("a2: " + a2); A a3 = (A) Class.forName("com.bjsxt.singleton.A").newInstance(); System.out.println("a3: " + a3);
3.对象的clone方法
A a3 = (A) a1.clone(); System.out.println("a3: " + a3);
4.getObject反序列化
FileOutputStream fos = new FileOutputStream("d:/a.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(a1); oos.close(); fos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/a.txt")); A a5 = (A) ois.readObject(); ois.close(); System.out.println("a5: " + a5);
类A的具体代码如下:
class A implements java.io.Serializable { public A clone() { return this; } }
结果如下:
a1: [email protected] a2: [email protected] a3: [email protected] a4: [email protected] a5: [email protected]
时间: 2024-12-16 23:37:47