方法1:静态编码&编译(new)
最常用的就是静态编写一个类,然后new一个对象
public class New {
public static void main(String[] args) {
New n = new New();
}
}
方法2:克隆(clone)
java提供克隆的手段来复制一个对象
浅克隆:
1.被复制的类需要实现Clonenable接口
2.Override clone()
public class Clone implements Cloneable{
private String name;
public Clone(String name){
this.name = name;
}
public void printName(){
System.out.println("My name is "+ name);
}
public void setName(String name) {
this.name = name;
}
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public static void main(String[] args) {
try {
Clone c = new Clone("Edwin Xu");
c.setName("Edwin Wang");
Clone clone = (Clone) c.clone();
clone.printName(); //My name is Edwin Wang
}catch (Exception e){
e.printStackTrace();
}
}
}
对于属性中有引用类型的,需要让该引用类型也继承Cloneable并重写clone(), 以实现深克隆。
如果类中有过多的引用类型就会很麻烦。
方法3:序列化与反序列化
序列化就是把对象写到流的过程,被写入流的对象是原对象的拷贝。
通过反序列化从流中重写构建出该对象,实现了真正的深度克隆。
public class Deserialization implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public Deserialization(String name){
this.name =name;
}
public void printName(){
System.out.println("My Name Is "+name);
}
public static void main(String[] args) {
try {
Deserialization d = new Deserialization("Edwin");
//序列化:打开一个流,写入
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));
out.writeObject(d);
out.close();
//反序列化:从流中取出来
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Deserialization d1 = (Deserialization)in.readObject();
in.close();
d1.printName();//My Name Is Edwin
}catch (Exception e){
e.printStackTrace();
}
}
}
方法4:反射
反射提供一种动态创建对象的方式
package reflection;
import java.lang.reflect.Constructor;
public class Reflection {
public Reflection(){
System.out.println("initializing");
}
public static void main(String[] args) {
try {
//方式1:Class.forName(full path)
Reflection r = (Reflection) Class.forName("reflection.Reflection").newInstance();
//方式2:ClassName.class
Reflection c1 = Reflection.class.newInstance();
//方式3:利用Constructor
Constructor<Reflection> con = Reflection.class.getConstructor();
Reflection r2 = con.newInstance();
}catch (Exception e){
e.printStackTrace();
}
}
}