用最简单的描述来区分new关键字和newInstance()方法的区别:
newInstance: 弱类型。低效率。只能调用无参构造。
new: 强类型。相对高效。能调用任何public构造。
newInstance( )是一个方法,而new是一个关键字,其次,Class下的newInstance()的使用有局限,因为它生成对象只能调用无参的构造函数,而使用new关键字生成对象没有这个限制。
Class.forName("")返回的是类
Class.forName("").newInstance()返回的是object
作为Java开发者,我们每天创建很多对象,但我们通常使用依赖管理系统,比如Spring去创建对象。然而这里有很多创建对象的方法,我们会在这篇文章中学到。
Java中有5种创建对象的方式,下面给出它们的例子还有它们的字节码:
使用new关键字
}→调用了构造函数
使用Class类的newInstance方法
} →调用了构造函数
使用Constructor类的newInstance方法
}→调用了构造函数
使用clone方法
} →没有调用构造函数
使用反序列化
} →没有调用构造函数
如果你运行了末尾的的程序,你会发现方法1,2,3用构造函数创建对象,方法4,5没有调用构造函数。
1.使用new关键字
这是最常见也是最简单的创建对象的方式了。通过这种方式,我们可以调用任意的构造函数(无参的和带参数的)。
2.使用Class类的newInstance方法
我们也可以使用Class类的newInstance方法创建对象。这个newInstance方法调用无参的构造函数创建对象。
我们可以通过下面方式调用newInstance方法创建对象:
或者:
Employee emp2 = Employee.class.newInstance();
3.使用Constructor类的newInstance方法
和Class类的newInstance方法很像, java.lang.reflect.Constructor类里也有一个newInstance方法可以创建对象。我们可以通过这个newInstance方法调用有参数的和私有的构造函数。
Constructor constructor = Employee.class.getConstructor();
这两种newInstance方法就是大家所说的反射。事实上Class的newInstance方法内部调用Constructor的newInstance方法。这也是众多框架,如Spring、Hibernate、Struts等使用后者的原因。
4.使用clone方法
无论何时我们调用一个对象的clone方法,jvm就会创建一个新的对象,将前面对象的内容全部拷贝进去。用clone方法创建对象并不会调用任何构造函数。
要使用clone方法,我们需要先实现Cloneable接口并实现其定义的clone方法。
Employee emp4 = (Employee) emp3.clone();
5.使用反序列化
当我们序列化和反序列化一个对象,jvm会给我们创建一个单独的对象。在反序列化时,jvm创建对象并不会调用任何构造函数。
为了反序列化一个对象,我们需要让我们的类实现Serializable接口
ObjectInputStream in =new ObjectInputStream(new FileInputStream("data.obj"));Employee emp5 = (Employee) in.readObject();
例子
让我们看一看为下面这个Employee类创建对象:
1 class Employee implementsCloneable, Serializable {2 private static final long serialVersionUID = 1L;3 privateString name;4 publicEmployee() {5 System.out.println("Employee Constructor Called...");6 }7 publicString getName() {8 returnname;9 }10 public voidsetName(String name) {11 this.name =name;12 }13 @Override14 public inthashCode() {15 final int prime = 31;16 int result = 1;17 result = prime * result + ((name == null) ? 0: name.hashCode());18 returnresult;19 }20 @Override21 public booleanequals(Object obj) {22 if (this ==obj)23 return true;24 if (obj == null)25 return false;26 if (getClass() !=obj.getClass())27 return false;28 Employee other =(Employee) obj;29 if (name == null) {30 if (other.name != null)31 return false;32 } else if (!name.equals(other.name))33 return false;34 return true;35 }36 @Override37 publicString toString() {38 return "Employee [name=" + name + "]";39 }40 @Override41 publicObject clone() {42 Object obj = null;43 try{44 obj = super.clone();45 } catch(CloneNotSupportedException e) {46 e.printStackTrace();47 }48 returnobj;49 }50 }
下面的Java程序中,我们将用5种方式创建Employee对象。
1 public classObjectCreation {2 public static void main(String... args) throwsException {3 //By using new keyword
4 Employee emp1 = newEmployee();5 emp1.setName("Naresh");6 System.out.println(emp1 + ", hashcode : " +emp1.hashCode());7 //By using Class class's newInstance() method
8 Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")9 .newInstance();10 //Or we can simply do this11 //Employee emp2 = Employee.class.newInstance();
12 emp2.setName("Rishi");13 System.out.println(emp2 + ", hashcode : " +emp2.hashCode());14 //By using Constructor class's newInstance() method
15 Constructor constructor = Employee.class.getConstructor();16 Employee emp3 =constructor.newInstance();17 emp3.setName("Yogesh");18 System.out.println(emp3 + ", hashcode : " +emp3.hashCode());19 //By using clone() method
20 Employee emp4 =(Employee) emp3.clone();21 emp4.setName("Atul");22 System.out.println(emp4 + ", hashcode : " +emp4.hashCode());23 //By using Deserialization24 //Serialization
25 ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));26 out.writeObject(emp4);27 out.close();28 //Deserialization
29 ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));30 Employee emp5 =(Employee) in.readObject();31 in.close();32 emp5.setName("Akash");33 System.out.println(emp5 + ", hashcode : " +emp5.hashCode());34 }35 }
程序会输出: