quarks
quarks

Reputation: 35282

Object deep cloning without Java reflection

What are the possibilities of doing deep object cloning without Java reflection? I have used Object cloning libraries that use reflection but AppEngine does not allow to do that.

So my existing application that worked with Tomcat not does not work.

Update:

Dozer library seems to be the best bet:

Mapper mapper = new DozerBeanMapper();
DestinationObject destObject =  mapper.map(sourceObject, DestinationObject.class);

Question would be if I don't need custom mapping can I just do the above as it is?

For example:

Cat cat = new Cat();

Mapper mapper = new DozerBeanMapper();
Cat newCat =  mapper.map(cat, Cat.class);

Update:

When I run my app with Dozer I get this error:

Caused by: java.lang.NoSuchMethodError: org.apache.commons.lang.StringUtils.contains(Ljava/lang/String;Ljava/lang/String;)Z
    at org.dozer.util.ResourceLoader.getResource(ResourceLoader.java:53)
    at org.dozer.util.DefaultClassLoader.loadResource(DefaultClassLoader.java:44)
    at org.dozer.config.GlobalSettings.loadGlobalSettings(GlobalSettings.java:116)
    at org.dozer.config.GlobalSettings.<init>(GlobalSettings.java:67)
    at org.dozer.config.GlobalSettings.<clinit>(GlobalSettings.java:46)

Looks like I am missing something, although I added Dozer using Maven.

Upvotes: 3

Views: 3019

Answers (3)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236034

Well, you can always do a deep clone by hand, just override the clone() method in your class(es). Very repetitive work, but feasible. And more efficient than using reflection, too.

Upvotes: 3

Domenic D.
Domenic D.

Reputation: 5366

Have you considered using Dozer?

[from their website]

Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

Dozer supports simple property mapping, complex type mapping, bi-directional mapping, implicit-explicit mapping, as well as recursive mapping. This includes mapping collection attributes that also need mapping at the element level.

Dozer not only supports mapping between attribute names, but also automatically converting between types. Most conversion scenarios are supported out of the box, but Dozer also allows you to specify custom conversions via XML.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533530

You can try ObjectOutputStream/ObjectInputStream. This uses reflection but your SecurityManager might allow it as you are not calling it directly.

Upvotes: 0

Related Questions