Java 中建立物件的方式
阿新 • • 發佈:2018-12-05
1. 使用new關鍵字建立物件
Student stu = new Student();
2. 使用Class類的newInstance方法(反射機制)
// 呼叫無參的構造器建立物件
Student stu = (Student) Class.forName("Student類全限定名").newInstance();
Student stu = Student.class.newInstance();
3. 使用Constructor類的newInstance方法(反射機制)
class Student {
private int id;
public Student(Integer id) {
this.id = id;
}
}
// 可以呼叫有引數的和私有的建構函式
Constructor<Student> constructor = Student.class.getConstructor(Integer.class);
Student stu = constructor.newInstance(123);
4. 使用Clone方法建立物件
class Student implements Cloneable {
@Override
public Object clone () throws CloneNotSupportedException {
return super.clone();
}
}
5. 使用(反)序列化機制建立物件
class Student implements Serializable {
private int id;
public Student(Integer id) {
this.id = id;
}
}
Student stu = new Student(123);
// 寫物件
ObjectOutputStream output = new ObjectOutputStream (new FileOutputStream("student.bin"));
output.writeObject(stu);
output.close();
// 讀物件
ObjectInputStream input = new ObjectInputStream(new FileInputStream("student.bin"));
Student stu = (Student) input.readObject();
System.out.println(stu);