Java中建立对象的5种不一样方法

做为Java开发者,咱们天天都会建立大量的对象,可是,咱们老是使用管理依赖系统(如Spring框架)来建立这些对象。其实还有其余方法能够建立对象,在接下来的文章中我会进行详细介绍。html

1.使用new关键字

这是最多见的建立对象的方法,而且也很是简单。经过使用这种方法咱们能够调用任何咱们须要调用的构造函数。java

Employee emp1 = new Employee();
0: new           #19          // class org/programming/mitra/exercises/Employee
 3: dup
 4: invokespecial #21          // Method org/programming/mitra/exercises/Employee."":()V

2.使用class类的newInstance方法

咱们也可使用class类的newInstance()方法来建立对象。此newInstance()方法调用无参构造函数以建立对象。框架

咱们能够经过newInstance() 用如下方式建立对象:ide

Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee").newInstance();

或者函数

Employee emp2 = Employee.class.newInstance();
51: invokevirtual    #70    // Method java/lang/Class.newInstance:()Ljava/lang/Object;

3.使用构造函数类的 newInstance方法

与使用class类的newInstance()方法类似,java.lang.reflect.Constructor类中有一个能够用来建立对象的newInstance()函数方法。经过使用这个newInstance()方法咱们也能够调用参数化构造函数和私有构造函数。this

Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
111: invokevirtual  #80  // Method java/lang/reflect/Constructor.newInstance:([Ljava/lang/Object;)Ljava/lang/Object;

这些 newInstance() 方法被认为是建立对象的反射手段。实际上,内部类的newInstance()方法使用构造函数类的 newInstance() 方法。这就是为何后者是首选而且使用不一样的框架如Spring, Hibernate, Struts等。code

4.使用clone方法

实际上不管什么时候咱们调用clone() 方法,JAVA虚拟机都为咱们建立了一个新的对象而且复制了以前对象的内容到这个新的对象中。使用 clone()方法建立对象不会调用任何构造函数。htm

为了在对象中使用clone()方法,咱们须要在其中实现可克隆类型并定义clone()方法。对象

Employee emp4 = (Employee) emp3.clone();
162: invokevirtual #87  // Method org/programming/mitra/exercises/Employee.clone ()Ljava/lang/Object;

5.使用反序列化

不管什么时候咱们对一个对象进行序列化和反序列化,JAVA虚拟机都会为咱们建立一个单独的对象。在反序列化中,JAVA虚拟机不会使用任何构造函数来建立对象。接口

对一个对象进行序列化须要咱们在类中实现可序列化的接口。

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();
261: invokevirtual  #118   // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;

正如咱们在以上的字节代码片断中所看到的,除第一种被转换为一个新的函数和一个 invokespecial 指令之外,其它4种方法都被调用并转换为invokevirtual。

示例

让咱们来看看准备建立对象的 Employee 类:

class Employee implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    public Employee() {
        System.out.println("Employee Constructor Called...");
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Employee [name=" + name + "]";
    }
    @Override
    public Object clone() {
        Object obj = null;
        try {
            obj = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return obj;
    }
}

在下面的Java程序中咱们用5种方式来建立 Employee对象。

public class ObjectCreation {
    public static void main(String... args) throws Exception {
        // By using new keyword
        Employee emp1 = new Employee();
        emp1.setName("Naresh");
        System.out.println(emp1 + ", hashcode : " + emp1.hashCode());
        // By using Class class's newInstance() method
        Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
                               .newInstance();
        // Or we can simply do this
        // Employee emp2 = Employee.class.newInstance();
        emp2.setName("Rishi");
        System.out.println(emp2 + ", hashcode : " + emp2.hashCode());
        // By using Constructor class's newInstance() method
        Constructor<Employee> constructor = Employee.class.getConstructor();
        Employee emp3 = constructor.newInstance();
        emp3.setName("Yogesh");
        System.out.println(emp3 + ", hashcode : " + emp3.hashCode());
        // By using clone() method
        Employee emp4 = (Employee) emp3.clone();
        emp4.setName("Atul");
        System.out.println(emp4 + ", hashcode : " + emp4.hashCode());
        // By using Deserialization
        // Serialization
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));
        out.writeObject(emp4);
        out.close();
        //Deserialization
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
        Employee emp5 = (Employee) in.readObject();
        in.close();
        emp5.setName("Akash");
        System.out.println(emp5 + ", hashcode : " + emp5.hashCode());
    }
}

此程序输出结果以下:

Employee Constructor Called...
Employee [name=Naresh], hashcode : -1968815046
Employee Constructor Called...
Employee [name=Rishi], hashcode : 78970652
Employee Constructor Called...
Employee [name=Yogesh], hashcode : -1641292792
Employee [name=Atul], hashcode : 2051657
Employee [name=Akash], hashcode : 63313419

本文译自:Dzone  译者:慧都控件网-慧都小艺

相关文章
相关标签/搜索