Cloneable questions

G

Guest

I want to clone a Vector WITH its elements. If any of its elements is
not Cloneable I want to return the element itself.
So the code is this:

--------------------
Vector v = .......;

Vector new_vector = new Vector();
for (int z = 0; z < v.size(); z++) {
Object o = v.elementAt(z);
if (o instanceof Cloneable)
o = ((Cloneable) o).clone(); // compile error
new_vector.add(o);
}
 
G

Guest

I want to clone a Vector WITH its elements. If any of its elements is
not Cloneable I want to return the element itself.
So the code is this:

--------------------
Vector v = .......;

Vector new_vector = new Vector();
for (int z = 0; z < v.size(); z++) {
Object o = v.elementAt(z);
if (o instanceof Cloneable)
o = ((Cloneable) o).clone(); // compile error
new_vector.add(o);
}
--------------------

Why I have compile error?
Is there a way to clone a Cloneable object upcasted to Object?
Or I must create an Interface Cloneable2 which refers to clone(); as
public?

Its to easy for my Objects:

public interface Clone {
public Object clone();
}

but for other Cloneable Objects?
 
T

Thomas Bühler

Hi
The Cloneable Interface itself doesn't define a clone() Method.
So you can't cast to Cloneable and call the clone() Method.
You have to define your own Clone Interface which define a clone() Method or
call the default clone via reflection call.

e.g.

public static Object cloneCallReflect(Object o) {
Method m = null;
if (o instanceof Cloneable) {
try {
m = o.getClass().getMethod("clone", (Class [])null);
return m.invoke(o, (Object[])null);
} catch (Exception e) {
e.printStackTrace();
}
}
// returns the original.
return o;
}

Best regards
Thomas Buehler
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top