栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【java】java创建对象的5种方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【java】java创建对象的5种方式

创建方式
方式解释
使用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;


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 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方法创建对象并不会调用任何构造函数。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/764194.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号