1、使用new关键字
Dog jack = new Dog();
2、使用Class类的newInstance方法
Class dogClass = Dog.class; //拿到class Dog的 Class实例对象
Dog rose = (Dog) dogClass.newInstance(); //调用Class的实例方法 newInstance()创建Dog的实例对象
3、使用Constructor类的newInstance方法
Constructor<Employee> constructor = Employee.class.getConstructor();
Dog jack = constructor.newInstance();
4、使用clone方法
public class CreateFour implements Cloneable {
public static void main(String args[]) {
CreateFour f = new CreateFour();
try {
CreateFour cloneObject = (CreateFour) f.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
5、使用反序列化
public class CreateFour implements Serializable {
public static void main(String args[]) {
CreateFour fCreateFour = new CreateFour();
ObjectOutputStream objectStream;
try {
objectStream = new ObjectOutputStream(new FileOutputStream("res/obj.txt"));
objectStream.writeObject(fCreateFour);
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("res/obj.txt"));
CreateFour cloneFour = (CreateFour) objectInputStream.readObject();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
6、总结
创建对象的5种方式,不管利用对象流,还是利用clone(),都会开辟新的内存空间,就是在jvm中的堆内存复制一个与源对象相同的新的对象(千万不要以为旧引用与新引用对应的是同一个对象)。