• 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();
            }
        }
    }
  • 相关阅读:
    Activiti服务类- HistoryService服务类
    Activiti服务类- FormService服务类
    Activiti工作流学习(一)——Activiti服务类
    Java中实现短信发送
    Windows Server 2016 搭建 SMB 共享文件
    QT安装简介
    C# MD5加密解密类 winform
    git版本控制系统--git客户端
    git版本控制系统--git远程仓库(局域网windows)
    git版本控制系统--git远程仓库(局域网linux)
  • 原文地址:https://www.cnblogs.com/heyjia/p/11319942.html
Copyright © 2020-2023  润新知