Java创建对象的几种方法

1.使用new关键字

Person person=new Person();

2.使用Class类的newInstance方法

  a)  Person ps=(Person) Class.forName("com.springioc.myioc.Person").newInstance();

    需要捕获ClassNotFoundException, IllegalAccessException, InstantiationException异常

  b) Person ps2=Person.class.newInstance();

    需要捕获IllegalAccessException, InstantiationException异常

3.使用Constructor类的newInstance方法

  a) Constructor<Person> constructor=Person.class.getConstructor();

    需要捕获NoSuchMethodException

    Person person=constructor.newInstance();

    需要捕获IllegalAccessException, InvocationTargetException, InstantiationException异常

  以上两种newInstance方法是通过反射来实现的

4.使用clone方法

  clone是object的方法,当我们调用一个对象的clone方法,jvm就会创建一个新的对象,将前面对象的内容全部拷贝进去。用clone方法创建对象并不会调用任何构造函数

  要使用clone方法,需要先实现Cloneable接口并实现其定义的clone方法

  Person person=new Person();

  Person pes=(Person).person.clone();

5.使用反序列化

  当我们序列化和反序列化一个对象,jvm会给我们创建一个单独的对象,在反序列化时,jvm创建对象并不会调用任何构造函数

  反序列化一个对象,需要让类实现Serializable接口

  Person person=new Person();

  person.setName("张三");

  person.setPassword("123456789");

  ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("obj.txt"));

  out.writeObject(person);

   out.close();

   ObjectInputStream in=new ObjectInputStream(new FileInputStream("obj.txt"));

    Person person1=(Person)in.readObject();

    in.close();

   System.out.println(person1.getName()+person1.getPassword());

 

posted on 2019-04-11 11:57  一个猎手  阅读(168)  评论(0编辑  收藏  举报

导航