简体   繁体   中英

How to clone an Object without knowing the exact type in Java?

public void test(Object obj){`
      Object newObj = obj;//reference

}

Without knowing the exact type of obj, how could I clone it such as something as Object newObj = obj.clone(); or Object newObj = new Object(obj);

The actual situation is: in a class Message I set a member HashMap<String,Object> to allow anyone which wanna use Message can add other properties/members instead of rewriting it. The object may be ArrarList<Integer> . Here comes the problem.

A safe way is to serialize the object, then deserialize. This ensures everything is a brand new reference. You'll have to implement the Serializable interface.

Google commons class org.apache.commons.lang.SerializationUtils provides this for you via the following method:

SerializationUtils.clone(Object);

Example:

this.myObjectCloned = SerializationUtils.clone(this.object);

Simple: you can't do that.

Unless you know that all objects that you will ever process / encounter followes certain rules, for example they allow serialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM