Reputation: 8563
I have created a clone of an object in my code.
Class<?> oc = o.getClass();
Object preStateInstance = oc.newInstance();
Now I have to output a Java file and I would like the created file to have an assignment of that cloned instance. Something like:
Object varX = preStateInstance.value;
Is that possible? How?
What I am trying to do is to create test cases. I want to save an instance of the object under test as a pre state value, in order to be able to compare the before and after state of an object. I have done it in my code, now I need to output it to a JUnit file. On the class that handles JUnit file writing I only have access to preStateInstance
.
EDIT: I think I still have not made myself clear. My JUnit writer requires me to pass on a string so that he will output it to a complete JUnit file. After cloning the instance I would have to tell my writer how to initialise it in it's file.
Upvotes: 1
Views: 251
Reputation: 3057
To create a clone you'll have to implement the Cloneable Interface and a clone method which creates the new object and copies the necessary attributes.
For your Unit-Tests however, I'd recommand some kind of serialization, have a look at XStream (http://x-stream.github.io/) It converts an object into XML and vice versa, allowing you to even edit the XML in between - just perfect for test cases IMHO.
Upvotes: 1
Reputation: 11
@Daniel, great answer.
if you are trying to save the object content to be able to read it back in when you run your tests you might be thinking of serialization
http://www.exampledepot.com/egs/java.io/SerializeObj.html
http://www.exampledepot.com/egs/java.io/DeserializeObj.html
Daniel's approach is even better, if you want to change the data by hand, serialization , stores in binary.
Upvotes: 0
Reputation: 298938
If you need to clone a Java Object, you can either use the built-in clone()
method (your class must implement Cloneable
). Or use one of the various Bean Property libraries (e.g. commons/beanutils) to transfer the state from one Object to another.
Upvotes: 0
Reputation: 220952
(public) members of classes can be accessed using reflection, too:
Field field = oc.getField("value");
Object varX = field.get(preStateInstance);
But be aware of these things:
Class.newInstance()
doesn't create a clone of o
. It creates a new instance of o
.Class.newInstance()
calls upon the default constructor. Be sure it is availableUpvotes: 0