在 Java 中创建对象的不同方式
以下是在Java中创建对象的不同方法。
使用新关键字-最常用的方法。使用new关键字调用任何构造函数来创建对象。
Testert=newTester();
使用.−使用加载类,然后调用其方法来创建对象。Class.forName()newInstance()Class.forName()newInstance()
Testert=Class.forName("Tester").newInstance();
使用clone()方法-通过调用其clone()方法获取所需对象的克隆对象。
Testert=newTester();
Testert1=t.clone();
使用反序列化-JVM在反序列化时创建一个新对象。
Testert=newTester();
ByteArrayOutputStreambyteArrayOutputStream=newByteArrayOutputStream();
objectOutputStream=newObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(t);
objectOutputStream.flush();
objectInputStream=newObjectInputStream(newByteArrayInputStream(byteArrayOutputStream.toByteArray()));
Testert1=objectInputStream.readObject();
使用反射-使用方法,我们可以创建一个新对象。Constructor.newInstance()
Constructorconstructor=Tester.class.getDeclaredConstructor();
Testerr=constructor.newInstance();
示例
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Tester implements Serializable, Cloneable {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String args[])
throws InstantiationException, IllegalAccessException
, ClassNotFoundException, CloneNotSupportedException
, IOException, NoSuchMethodException, SecurityException
, IllegalArgumentException, InvocationTargetException {
//场景一:使用new关键字
Tester t = new Tester();
System.out.println(t);
//场景2:使用Class.forName().newInstance()
Tester t1 = (Tester) Class.forName("Tester").newInstance();
System.out.println(t1);
//场景3:使用clone()方法
Tester t3 = (Tester) t.clone();
System.out.println(t3);
//场景四:使用反序列化方法
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(t);
objectOutputStream.flush();
ObjectInputStream objectInputStream = new ObjectInputStream(
new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
Tester t4 = (Tester) objectInputStream.readObject();
System.out.println(t4);
//场景5:使用反射方法
Constructor constructor = Tester.class.getDeclaredConstructor();
Tester t5 = constructor.newInstance();
System.out.println(t5);
}
} 输出结果Tester@2a139a55 Tester@15db9742 Tester@6d06d69c Tester@55f96302 Tester@3d4eac69