首页 > 编程语言 > 详细

java创建对象的5种方式

时间:2020-07-09 22:15:00      阅读:92      评论:0      收藏:0      [点我收藏+]

1、使用new关键字

2、利用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor类的newInstance()实例方法

3、构造函数的newInstance()方法

4、对象的反序列化

5、对象的clone()方法

下面详细看看这5种方法的简单实现:

1、使用new关键字

public class Test {

    private String name;
    public Test() {
    }

    public Test(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Test t1 = new Test();
        Test t2 = new Test("张三");
    }
}

2、利用反射

首先通过Class.forName()动态加载类的class对象,然后通过newInstance()方法获得Test对象,这里使用的是上面的Test对象

public static void main(String[] args) throws Exception{
        String className="com.qml.test";
        Class clasz=Class.forName(className);
        Test t=(Test)clasz.newInstance();
}

3、构造函数对象的newInstance()方法

类Constructor也有newInstance方法,这一点和Class有点像。从它的名字可以看出它与Class的不同,Class是通过类来创建对象,而Constructor则是通过构造器。依然使用第一个例子中的Test类。

public static void main(String[] args) throws Exception {
    Constructor<Test> constructor;
   try {
        constructor = Test.class.getConstructor();
       Test t = constructor.newInstance();
   } catch (InstantiationException |
        IllegalAccessException |
        IllegalArgumentException |
        InvocationTargetException |
        NoSuchMethodException |
        SecurityException e) {
        e.printStackTrace();
   }
}

4、对象反序列化

继承Serializable接口

public class Test implements Serializable{

    private String name;
    public Test() {
    }

    public Test(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) throws Exception {
       String filePath = "sample.txt";
     Test t1 = new Test("张三");
     try {
        FileOutputStream fileOutputStream =
               new FileOutputStream(filePath);
        ObjectOutputStream outputStream =
               new ObjectOutputStream(fileOutputStream);
        outputStream.writeObject(t1);
        outputStream.flush();
        outputStream.close();

        FileInputStream fileInputStream =
               new FileInputStream(filePath);
        ObjectInputStream inputStream =
               new ObjectInputStream(fileInputStream);
        Test t2 = (Test) inputStream.readObject();
        inputStream.close();
        System.out.println(t2.getName());
     } catch (Exception ee) {
           ee.printStackTrace();
     }
    }
}


5、对象的clone()方法

public static void main(String[] args) throws Exception {
    Test t1 = new Test("张三");
    Test t2 = (Test) t1.clone();
    System.out.println(t2.getName());
}

 

java创建对象的5种方式

原文:https://www.cnblogs.com/qml0725/p/13276510.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!