java实例化对象的五种方式

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();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值