Java中创建对象的5种方式

作为Java开发者,我们每天创建很多对象,但我们通常使用依赖管理系统,比如Spring去创建对象。然而这里有很多创建对象的方法,我们会在这篇文章中学到。

Java中有5种创建对象的方式,下面给出它们的例子还有它们的字节码

使用new关键字调用构造函数
使用class类的newInstance()方法调用构造函数
使用Constructor类的newInstance()方法调用构造函数
使用clone方法没有调用构造函数
  

代码如下:

先建立Student类

public class Student implements Cloneable{

    public void sayHello(){
        System.out.println("hello!");
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

测试类:

public class Test{

    //1、使用new关键字
    public static  void one(){
        Student s1 = new Student();
        s1.sayHello();
    }

    //2、使用newInstance方法
    public static void two() throws Exception{
        Student s2 = (Student)Class.forName("Student").newInstance();
        s2.sayHello();
    }
    //3、使用newInstance方法
    public static void three() throws Exception{
        Student s3 = Student.class.newInstance();
        s3.sayHello();
    }

    //4、使用Constructor类的newInstance方法
    public static void four() throws Exception{
        Constructor<Student> constructor = Student.class.getConstructor();
        Student s4 = constructor.newInstance();
        s4.sayHello();
    }

    //5、使用clone方法
    public static void five()  throws Exception{
        Constructor<Student> constructor = Student.class.getConstructor();
        Student s4 = constructor.newInstance();
        Student s5 = (Student)s4.clone();
        s5.sayHello();
    }

    public static void six() throws Exception{

    }
    public static void main(String[] args) throws Exception{
//        one();
//        two();
//        three();
//        four();
        five();
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网极客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值