Java对象的创建

来源:互联网 发布:甘肃政法学院网络教学 编辑:程序博客网 时间:2024/05/26 02:51

Java对象的创建

创建方法如下:

  1. 使用new关键字
  2. 使用对象的clone方法
  3. 使用反序列化
  4. 使用Class类的newInstance方法
  5. 使用Constructor的类的newInstance方法

方式一

        Person lamZe = new Person("lamZe", 18);

方式二
/**
* 使用clone方法创建对象
* 步骤:
* 1、要创建的对象的类实现Cloneable接口
* 2、重写clone方法
*/

        Person lamze2 = (Person) lamze.clone();

方式三
/**
* 使用反序列化创建对象
* 1、实现Serializable接口(一个标记可以序列化的接口)
* 2、使用ObjectInputStream读取对象
*/

        //反序列化        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream("d:/Person.Obj"))) {            Person person = (Person) in.readObject();            System.out.println(person+":"+person.hashCode());        }catch (FileNotFoundException |ClassNotFoundException  e) {            e.printStackTrace();        }catch (IOException e) {            e.printStackTrace();        }

方式四
/**
* 使用Class的newInstance方法
* 注意:只能调用 类的无参构造器
*/

        Class<Person> clazz = Person.class;        try {            Person person = clazz.newInstance();            System.out.println(person);        } catch (InstantiationException | IllegalAccessException e) {            e.printStackTrace();        }

方式五
/**
* 使用Constructor的newInstance创建对象
*
*/

        Class<Person> clzz = Person.class;        try {            Constructor<Person> constructor = clzz.getConstructor(String.class, int.class);            try {                Person person = constructor.newInstance("lamZe",18);                System.out.println(person);            } catch (IllegalAccessException|InvocationTargetException|InstantiationException e) {                e.printStackTrace();            }        } catch (NoSuchMethodException e) {            e.printStackTrace();        }

这里有完整的代码

作为blog的第一篇文章,我觉得以这个为题是不错的选择了。

原创粉丝点击