Java中创建对象的几种方式与详解

https://www.cnblogs.com/wxd0108/p/5685817.html
https://blog.csdn.net/hustzw07/article/details/72518298

#Java中创建对象的5种方式
使用new关键字 } → 调用了构造函数
使用Class类的newInstance方法 } → 调用了构造函数
使用Constructor类的newInstance方法 } → 调用了构造函数
使用clone方法 } → 没有调用构造函数
使用反序列化 } → 没有调用构造函数

##1.使用new关键字
这是最常见也是最简单的创建对象的方式了。通过这种方式,我们可以调用任意的构造函数(无参的和带参数的)。

Student student = new Student();

##2.Class类的newInstance方法

Student student2 = (Student)Class.forName(className).newInstance();   
// 或者:  
Student stu = Student.class.newInstance();  

JDK1.8,class类的源码

public final class Class<T> implements java.io.Serializable,  
                              GenericDeclaration,  
                              Type,  
                              AnnotatedElement {  
    // other code  
                               
    public T newInstance()  
        throws InstantiationException, IllegalAccessException  
    {  
        // ...  
  
        // Constructor lookup  
        // other code   
        if (cachedConstructor == null) {  
            if (this == Class.class) {  
                throw new IllegalAccessException(  
                    "Can not call newInstance() on the Class for java.lang.Class"  
                );  
            }  
            try {  
                // ...  
                final Constructor<T> c = getConstructor0(empty, Member.DECLARED);  
                // 1. 构造函数是公有的或者方法可见  
                // ...  
                cachedConstructor = c;  
            } catch (NoSuchMethodException e) {  
                throw (InstantiationException)  
                    new InstantiationException(getName()).initCause(e);  
            }  
        }  
        Constructor<T> tmpConstructor = cachedConstructor;  
        // ...  
        // Run constructor  
        try {  
            return tmpConstructor.newInstance((Object[])null);// 2. 无参构造函数  
        } catch (InvocationTargetException e) {  
            // ...  
        }  
    }  
  
    // other code  
}  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值