1. 程式人生 > 實用技巧 >Java建立物件的五種方式

Java建立物件的五種方式

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Constructor;
public class Student {

public void method(){
System.out.println("Hello");
}
public static void main(String[] args) throws Exception {

//通過new呼叫了無參構造建立物件
Student student1 = new Student();
student1.method();
//通過Class類中的newInstance建立物件
Student student2 = Student.class.newInstance();
student2.method();
//通過Constructor中的newInstance建立物件
Constructor<Student> constructor = Student.class.getConstructor();
Student student3 = constructor.newInstance();
student3.method();
//通過clone建立物件
Student student4 =(Student) student3.clone();
student4.method();
//通過序列化和反序列化建立物件
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("檔名"));
Student student5 = (Student)objectInputStream.readObject();
student5.method();
}
}