JAVA獲取對象的四種方式


1.使用new創建對象

2.通過反射的方式

3.通過clone的方式

4.通過反序列化的方式

一.使用new創建對象

  使用new會增加耦合度,所以要盡量減少使用new的頻率。並且new是使用強引用方式來創建對象的。

Hello hello = new Hello();

二.使用反射的方式創建對象

      1.使用Class類的newInstance方法來創建對象

Class class = Class.forname("com.heyjia.test.Hello");
Hello hello = (Hello)class.newInstance();

      2.使用Constructor類的newInstance方法來創建兌現

    Class class = Class.forName("com.heyjia.test.Hello");
    Constructor constructor = class.getConstructor();
    Hello hello = (Hello)constructor.newInstance();

三.使用clone的方式創建對象

   前提:需要有一個對象,使用該對象父類的clone方法可以創建一個內存大小跟它一樣大的對象

Hello hello1 = new Hello();
Hello hello2 = (Hello)hello1.clone();

四.使用反序列化的方式創建對象

   在通過實現序列化serializable接口將對象存到硬盤中,通過反序列化可以獲取改對象

public class Serialize
{
    public static void main(String[] args)
    {
        Hello h = new Hello();

        //准備一個文件用於存儲該對象的信息
        File f = new File("hello.obj");

        try(FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            FileInputStream fis = new FileInputStream(f);
            ObjectInputStream ois = new ObjectInputStream(fis)
            )
        {
            //序列化對象,寫入到磁盤中
            oos.writeObject(h);
            //反序列化對象
            Hello newHello = (Hello)ois.readObject();

            //測試方法
            newHello.sayWorld();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM