天天看點

如果一個産品經理不懂得技術的話,那麼TA一定走不遠的。如果一個技術經理疏于技術的話,那麼TA一定會完蛋的。問題來了,Ja

作者:MysteryHunter

如果一個産品經理不懂得技術的話,那麼TA一定走不遠的。如果一個技術經理疏于技術的話,那麼TA一定會完蛋的。

問題來了,Java執行個體化對象有幾種方法呢?比較讓人失望的是居然有工作8年的Java資深工程師居然答不上來這個問題。

一般來說就4種方法:

1.通過最常見的new方法。

2.通過反射(這裡反射有三種寫法)。

3.通過對象流反序列化。

4.通過對象拷貝(非常不推薦)。

talk is cheap, show me your code!

class O implements Serializable, Cloneable {

    public int x;

    public int y;

    public O() {

    }

    public O(int x, int y) {

        this.x = x;

        this.y = y;

    }

    @Override

    protected Object clone() throws CloneNotSupportedException {

        return super.clone();

    }

}

public class HowToInstanceObject {

    public static void main(String[] args) {

        // normal case

        O o1 = new O();

        System.out.println(o1);

        // reflect1 case

        O o2 = (O) Class.forName("O").newInstance();

        System.out.println(o2);

        // reflect2 case

        O o3 = O.class.newInstance();

        System.out.println(o3);

        // reflect3-1 case - use the default constructor

        Class<O> oClazz = O.class;

        Constructor<O> cClazz1 = oClazz.getDeclaredConstructor();

        O o4 = cClazz1.newInstance();

        System.out.println(o4);

        // reflect3-2 case - use the custom constructor

        Constructor<O> cClazz2 = oClazz.getDeclaredConstructor(int.class, int.class);

        O o5 = cClazz2.newInstance(10, 20);

        System.out.println(o5);

        /*

         * object stream case

         * @description always use in transferring data via network, here use it via local file

         */

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("O.ser"));

        O o6 = (O) ois.readObject();

        System.out.println(o6);

        // shallow copy case : not recommended to use in Instancing object

        O tempO2 = new O(34, 41);

        O o7 = (O) tempO2.clone();

        System.out.println(o7);

    }

}

代碼看截圖。

反射方法,你一定要會,因為你的飯碗跟Spring技術體系有很大關系,Spring容器說白了就是依賴反射的。

對象流反序列化,RPC架構就是依賴它在網絡進行資料傳輸的。

好了,隻是淺談一下。歡迎評論區補充。

如果一個産品經理不懂得技術的話,那麼TA一定走不遠的。如果一個技術經理疏于技術的話,那麼TA一定會完蛋的。問題來了,Ja
如果一個産品經理不懂得技術的話,那麼TA一定走不遠的。如果一個技術經理疏于技術的話,那麼TA一定會完蛋的。問題來了,Ja
如果一個産品經理不懂得技術的話,那麼TA一定走不遠的。如果一個技術經理疏于技術的話,那麼TA一定會完蛋的。問題來了,Ja
如果一個産品經理不懂得技術的話,那麼TA一定走不遠的。如果一個技術經理疏于技術的話,那麼TA一定會完蛋的。問題來了,Ja