创建方式
方式 解释 使用new关键字 调用了构造函数 使用Class的newInstance方法 调用了构造函数 使用Constructor类的newInstance方法 调用了构造函数 使用clone方法 没有调用构造函数 使用反序列化 没有调用构造函数
案例,步骤
1、先创建实例类
package jvm. entity;
public class Human implements Cloneable , Serializable {
private String name;
private Integer age;
public Human ( ) { }
public Human ( String name, Integer age) {
this . name = name;
this . age = age;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public Integer getAge ( ) {
return age;
}
public void setAge ( Integer age) {
this . age = age;
}
@Override
public Object clone ( ) throws CloneNotSupportedException {
return super . clone ( ) ;
}
}
2、创建测试类
package jvm. createObj;
import com. alibaba. fastjson. JSONObject;
import jvm. entity. Human;
import java. lang. reflect. Constructor;
import java. lang. reflect. InvocationTargetException;
public class CreateObj {
public static void main ( String[ ] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, CloneNotSupportedException {
Human newObject = new Human ( "walker" , 18 ) ;
System. out. println ( newObject) ;
Human newInstance = Human. class . newInstance ( ) ;
System. out. println ( newInstance) ;
Constructor< Human> constructor = Human. class . getConstructor ( ) ;
Human constructorObj = constructor. newInstance ( ) ;
System. out. println ( constructorObj) ;
Human cloneObj = ( Human) newObject. clone ( ) ;
System. out. println ( cloneObj) ;
String json= "{\n" +
"\"name\":\"walker\",\n" +
"\"age\":18}" ;
Human jsonObj = JSONObject. parseObject ( json, Human. class ) ;
System. out. println ( jsonObj) ;
}
}
区别
使用new创建对象是最常见的方式,是会调用到构造方法的 使用Class的newInstance方法和使用Constructor类的newInstance方法是运用到了java的反射 使用clone方法jvm就会创建一个新的对象,将前面对象的内容全部拷贝进去。用clone方法创建对象并不会调用任何构造函数。