JAVA中創建對象的四種方式


/**
 * <p>
 * Title: 創建對象的四種方式
 * </p>
 * 
 * 
 * @author lwx
 * @version 1.0
 * @create 2013 1 17 14:03:35
 */
public class CreateObj implements Cloneable,Serializable{
    private static String filename = CreateObj.class.getResource("").getPath()
            + "/obj.txt";
    static File file = new File(filename);
    static {
        if (!file.exists())
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    }

    public static void main(String[] args) throws Exception {
        // 1.第一種常用方式
        CreateObj s1 = new CreateObj();
        System.out.println(s1);
        // 2.第二種方式 靜態方式 java.lang.InstantiationException
        CreateObj s2 = (CreateObj) Class.forName(
                "com.newland.commons.collectionutil.CreateObj").newInstance();
        System.out.println(s2);
        //第三種方式 用對象流來實現 前提是對象必須實現 Serializable
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                new FileOutputStream(filename));
        objectOutputStream.writeObject(s2);
        ObjectInput input=new ObjectInputStream(new FileInputStream(filename));
        CreateObj s3 = (CreateObj) input.readObject();
        System.out.println(s3);
        //第四種 clone 必須 實現Cloneable接口 否則拋出CloneNotSupportedException
        CreateObj obj=new CreateObj();
        CreateObj s4= (CreateObj) obj.clone();
        System.out.println(s4);
    }
}

關於clone的介紹:http://www.blogjava.net/jerry-zhaoj/archive/2009/10/14/298141.html


免責聲明!

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



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