1、用new语句创建对象,这是最常见的创建对象的方法。
Student student = new Student();
2、通过工厂方法返回对象,如:String str = String.valueOf(23);
public interface Factory{
Product createProduct();
}
public class ConcreateFactory implements Factory{
}
public Product createProduct(){
return new ConcreateProduct();
}
public class ConcreateProduct implements Product{}
}
public interface Product{}
private Factory factory;
public class Client{
this.factory = factory;
public Client(Factory factory){ }
Product product = factory.createProduct();
public void dosomething(){ }
Client client = new Client(new ConcreateFactory());
public static void main(String[] args){ client.dosomething(); }
}
3、运用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor类的newInstance()实例方法。如:Object obj = Class.forName("java.lang.Object").newInstance();
c1 = Class.forName('com.ghgj.reflect.Student');
Student student3 = (Student)c1.newInstance();
4、调用对象的clone()方法。Student student2 = (Student) student.clone()
Student student2 = (Student) student.clone();
5、通过I/O流(包括反序列化),如运用反序列化手段,调用java.io.ObjectInputStream对象的 readObject()方法。
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream("C:/student.txt"));
out.writeObject(student);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:/student.txt"));
Student student4 = (Student)in.readObject();
in.close();