实例化类的四种方式
实例化类有四种方式:
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: com.bjsxt.singleton.A@1f6226 a2: com.bjsxt.singleton.A@64ea66 a3: com.bjsxt.singleton.A@158f9d3 a4: com.bjsxt.singleton.A@1f6226 a5: com.bjsxt.singleton.A@13f7281