1、Java程序中创建对象的5种常见方式

  在讲Jvm对字符串的处理之前,我们先来讲一下,在Java中,常见的5种创建对象的方式:

  1)通过关键字new调用构造器创建Java对象,eg:String str = new String("hello");

  2)通过Class对象的newInstance()方法调用构造器创建Java对象,eg:Class.forName("com.mysql.jdbc.Driver").newInstance();

  3)通过Java的反序列化机制从IO流中恢复Java对象,eg:

package test;
 
 import java.io.Serializable;
 
 public class Person implements Serializable {
 
     static final long serialVersionUID = 1L;
 
     String name; // 姓名
 
     public Person() {}
   
     public Person(String name) {
         super();
         this.name = name;
     }
 }

package test;
 
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 
 public class ObjectIo {
     public static void main(String[] args) throws Exception {
         Person p = new Person("小明");
         FileOutputStream fos = new FileOutputStream("d:/objectIoTest.dat");
         ObjectOutputStream oos = new ObjectOutputStream(fos);
         oos.writeObject(p);
         oos.flush();
         oos.close();    //前面这几行都是为了下面几行通过Java的反序列化机制从IO流中恢复Java对象作准备
       
         //下面才是开始通过Java的反序列化机制从IO流中恢复Java对象
         FileInputStream fis = new FileInputStream("d:/objectIoTest.dat");
         ObjectInputStream ois = new ObjectInputStream(fis);
         Person person = (Person) ois.readObject();
         System.out.println("这个人是 : " + person.name);
     }
 }

  运行结果:

  4)通过Java对象提供的clone()方法复制一个新的Java对象,eg:

package test;
 
 /**
  * 必须实现Cloneable接口,并且重写clone()方法
  * @ClassName: Base
  * @author 小学徒
  * @date 2013-3-28
  */
 public class Base implements Cloneable{
     int i = 20;
   
     @Override
     protected Object clone() throws CloneNotSupportedException {
         return super.clone();
     }
 }

package test;
 
 public class CloneTest {
     public static void main(String[] args) throws Exception {
         Base b = new Base();
         Base c = (Base) b.clone();
         System.out.println("b和c是同一个对象? " + (c == b));
     }
 }