【Java】创建对象的几种方式
1.new创建新的对象
String str = new String("str");
2.通过Java的反射机制
public static void main(String[] args) throws Exception {
// 获取类的Class对象
String str = (String)Class.forName("java.lang.String").newInstance();
System.out.println(str);
}
3.通过clone机制(克隆机制)
=========================Myclass.java===========================================
public class MyClass implements Cloneable { private int value;public MyClass(int value) { this.value = value; } public int getValue() { return value; } @Override public MyClass clone() throws CloneNotSupportedException { return (MyClass) super.clone(); }}
=Main.java===================
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
MyClass obj1 = new MyClass(10);
MyClass obj2 = obj1.clone();System.out.println(obj1.getValue()); // 输出:10 System.out.println(obj2.getValue()); // 输出:10 }}
4.通过序列化机制
通过序列化机制来创建新的对象。序列化是将对象转换为字节流的过程,以便可以将其存储在磁盘上或通过网络传输。反序列化则是将字节流转换回对象的过程。
===================================================================================================
import java.io.*;public class MyClass implements Serializable {
private int value;
public MyClass(int value) {
this.value = value;
}public int getValue() { return value; } private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(value * 2); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { value = in.readInt(); }}
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
MyClass obj1 = new MyClass(10);
FileOutputStream fileOut = new FileOutputStream("obj1.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj1);
out.close();
fileOut.close();FileInputStream fileIn = new FileInputStream("obj1.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); MyClass obj2 = (MyClass) in.readObject(); in.close(); fileIn.close(); System.out.println(obj1.getValue()); // 输出:10 System.out.println(obj2.getValue()); // 输出:20 }}
5、构造函数对象的newInstance()方法
类Constructor也有newInstance方法,这一点和Class有点像。从它的名字可以看出它与Class的不同,Class是通过类来创建对象,而Constructor则是通过构造器。依然使用第一个例子中的Test类。
public static void main(String[] args) throws Exception {
Constructor<Test> constructor;
try {
constructor = Test.class.getConstructor();
Test t = constructor.newInstance();
} catch (InstantiationException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException |
NoSuchMethodException |
SecurityException e) {
e.printStackTrace();
}
}



浙公网安备 33010602011771号