四種創建對象的方法

(1) 用new語句創建對象,這是最常見的創建對象的方法。
(2) 運用反射手段,調用java.lang.Class或者java.lang.reflect.Constructor類的newInstance()實例方法。
(3) 調用對象的clone()方法。
(4) 運用反序列化手段,調用java.io.ObjectInputStream對象的 readObject()方法。

一.用new語句創建對象
Java代碼

User user = new User()  

二.運用反射手段
(1)調用java.lang.Class.newInstance()
Java代碼

Class.forName(classname).newInstance()  
Wife wife = (Wife) Class.forName("com.java.clone.Wife").newInstance();  

(2)調用java.lang.reflect.Constructor類的newInstance()
Java代Constructor constructor = Wife.class.getDeclaredConstructor(int.class,String.class);
Wife wife = (Wife) constructor.newInstance(1,”nihao”); .調用對象的clone()方法
詳情參考:http://ncs123.iteye.com/blog/1775631

Java代碼

Wife wife = new Wife(1,"wang");  
Wife wife2 = null;  
wife2 = (Wife) wife.clone();//運用clone()方法產生新對象  

四.運用反序列化手段
被序列化的對象必須implements Serializable
Java代碼

public class BeanUtil {  

    @SuppressWarnings("unchecked")  
    public static <T> T cloneTo(T src) throws RuntimeException {  
        ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream();  
        ObjectOutputStream out = null;  
        ObjectInputStream in = null;  
        T dist = null;  

        try {  
            out = new ObjectOutputStream(memoryBuffer);  
            out.writeObject(src);  
            out.flush();  
            in = new ObjectInputStream(new ByteArrayInputStream(  
                    memoryBuffer.toByteArray()));  
            dist = (T) in.readObject();  

        } catch (Exception e) {  
            throw new RuntimeException(e);  
        } finally {  
            if (out != null)  
                try {  
                    out.close();  
                    out = null;  
                } catch (IOException e) {  
                    throw new RuntimeException(e);  
                }  
            if (in != null)  
                try {  
                    in.close();  
                    in = null;  
                } catch (IOException e) {  
                    throw new RuntimeException(e);  
                }  
        }  

        return dist;  
    }  

    public static void main(String[] args){  
        Husband husband = new Husband(1);  
        Wife wife = new Wife(1,"jin");  
        husband.setWife(wife);  
        Husband husband2 = cloneTo(husband);//運用反序列生成了一個對象  
    }  
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章