创建方式
| 方式 | 解释 |
|---|---|
| 使用new关键字 | 调用了构造函数 |
| 使用Class的newInstance方法 | 调用了构造函数 |
| 使用Constructor类的newInstance方法 | 调用了构造函数 |
| 使用clone方法 | 没有调用构造函数 |
| 使用反序列化 | 没有调用构造函数 |
案例,步骤
1、先创建实例类
package jvm.entity;
//1、继承Cloneable接口,这里是为了实现通过clone创建对象
//实现序列化接口,是为了实现序列化和反序列化功能
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;
}
//重写clone()方法,这里默认的访问符号是protected,这里为了测试,将其修改了public
@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;
/**
* @Author: WalkerShen
* @DATE: 2022/3/14
* @Description: 创建对象的方式
**/
public class CreateObj {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, CloneNotSupportedException {
/**
* 方式一:使用new
*/
Human newObject = new Human("walker", 18);
System.out.println(newObject);
/**
* 方式二:使用class newInstance
*/
Human newInstance = Human.class.newInstance();
System.out.println(newInstance);
/**
* 方式三:使用构造器
*/
Constructor<Human> constructor = Human.class.getConstructor();
Human constructorObj = constructor.newInstance();
System.out.println(constructorObj);
/**
* 方式四:使用clone
* 对应的类需要继承Cloneable接口,然后重写clone方法
*/
Human cloneObj = (Human) newObject.clone();
System.out.println(cloneObj);
/**
* 方式五:反序列化
*相当于将json转成对象
*/
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方法创建对象并不会调用任何构造函数。
版权声明:本文为Think_and_work原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。