如果一个产品经理不懂得技术的话,那么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框架就是依赖它在网络进行数据传输的。
好了,只是浅谈一下。欢迎评论区补充。