Java代码创建对象的六种方法分享
下文笔者讲述java代码创建对象的六中方法分享,如下所示
Java代码创建对象的6种方法
1.使用new关键字
TestClass p1 = new TestClass();
2.反射之Class类newInstance()
TestClass p2 = TestClass.class.newInstance();
3.反射之Constructor类的newInstance()
TestClass p3 = TestClass.class.getDeclaredConstructor().newInstance();
4.Object对象的clone方法
TestClass p4 = (TestClass) p1.clone();
注意Object类的clone方法是protected
在Override时,可修改为public
5.反序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.bin"));
oos.writeObject(p1);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.bin"));
TestClass p5 = (TestClass) ois.readObject();
ois.close();
TestClass类必须要实现Serializable接口
6.使用Unsafe类
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
TestClass p6 = (TestClass) unsafe.allocateInstance(TestClass.class);
例
package com.java265.basic;
import sun.misc.Unsafe;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class CreateObject {
public static class TestClass implements Cloneable, Serializable {
public TestClass(){
System.out.println("Constructor called");
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args)
throws IllegalAccessException, InstantiationException,
NoSuchMethodException, InvocationTargetException,
CloneNotSupportedException, IOException,
ClassNotFoundException, NoSuchFieldException {
System.out.println("---start---");
System.out.println("(1) new");
TestClass p1 = new TestClass();
System.out.println("(2) Class newInstance");
TestClass p2 = TestClass.class.newInstance();
System.out.println("(3) Constructor newInstance");
TestClass p3 = TestClass.class.getDeclaredConstructor().newInstance();
System.out.println("(4) clone");
TestClass p4 = (TestClass) p1.clone();
System.out.println("(5)Serialization");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("testclass.bin"));
oos.writeObject(p1);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("testclass.bin"));
TestClass p5 = (TestClass) ois.readObject();
ois.close();
System.out.println("(6) Unsafe");
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
TestClass p6 = (TestClass) unsafe.allocateInstance(TestClass.class);
System.out.println("---end---");
}
}
-----运行以上代码,将输出以下信息------
---start---
(1) new
Constructor called
(2) Class newInstance
Constructor called
(3) Constructor newInstance
Constructor called
(4) clone
(5)Serialization
(6) Unsafe
---end---
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


