java创建对象完成初始化6_深入理解Java对象的创建过程:类的初始化与实例化

一、Java对象创建时机

这是我们最常见的也是最简单的创建对象的方式,通过这种方式我们可以调用任意的构造函数(无参的和有参的)去创建对象。

Student student = new Student();

2). 使用Class类的newInstance方法(反射机制)

我们也可以通过Java的反射机制使用Class类的newInstance方法来创建对象,事实上,这个newInstance方法调用无参的构造器创建对象,比如

Student student2 = (Student)Class.forName("Student类全限定名").newInstance();

或者:

Student stu = Student.class.newInstance();

3). 使用Constructor类的newInstance方法(反射机制)   java.lang.relect.Constructor类里也有一个newInstance方法可以创建对象,该方法和Class类中的newInstance方法很像,但是相比之下,Constructor类的newInstance方法更加强大些,我们可以通过这个newInstance方法调用有参数的和私有的构造函数,比如: ---

public classStudent {private intid;publicStudent(Integer id) {this.id =id;

}public static voidmain(String[] args) throws Exception {

Constructor constructor = Student.class.getConstructor(Integer.class);

Student stu3= constructor.newInstance(123);

}

}

使用newInstance方法的这两种方式创建对象使用的就是Java的反射机制,事实上Class的newInstance方法内部调用的也是Constructor的newInstance方法。

4). 使用Clone方法创建对象

无论何时我们调用一个对象的clone方法,JVM都会帮我们创建一个新的、一样的对象,特别需要说明的是,用clone方法创建对象的过程中并不会调用任何构造函数。关于如何使用clone方法以及浅克隆/深克隆机制,笔者已经在博文《 Java String 综述(下篇)》做了详细的说明。简单而言,要想使用clone方法,我们就必须先实现Cloneable接口并实现其定义的clone方法,这也是原型模式的应用。比如:

public class Student implements Cloneable{

private int id;

public Student(Integer id) {

this.id = id;

}

@Override

protected Object clone() throws CloneNotSupportedException {

// TODO Auto-generated method stub

return super.clone();

}

public static void main(String[] args) throws Exception {

Constructor constructor = Student.class

.getConstructor(Integer.class);

Student stu3 = constructor.newInstance(123);

Student stu4 = (Student) stu3.clone();

}

}

6). 完整实例

public class Student implements Cloneable, Serializable {

private int id;

public Student(Integer id) {

this.id = id;

}

@Override

public String toString() {

return "Student [id=" + id + "]";

}

public static void main(String[] args) throws Exception {

Constructor constructor = Student.class

.getConstructor(Integer.class);

Student stu3 = constructor.newInstance(123);

// 写对象

ObjectOutputStream output = new ObjectOutputStream(

new FileOutputStream("student.bin"));

output.writeObject(stu3);

output.close();

// 读对象

ObjectInputStream input = new ObjectInputStream(new FileInputStream(

"student.bin"));

Student stu5 = (Student) input.readObject();

System.out.println(stu5);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值