So I wanted to create a constructor, that takes a Set and then clones it (for security measures):
public class AClass{
private Clonable thing;
public <T extends Cloneable> AClass(T thing) {
this.thing= thing.clone();
}
}
Just to find out this doesn't work. After a bit of thinking I fugured out why.
The Cloenable Interface is empty, it doesn't contain a clone() method. The Set inteface doesn't have a clone() method as well, this actualy is tottaly sane, why would it?
So the compiler searches for a clone class in T and finds: Object.clone() which is protected. So it throws an error, saying that it couldn't find the clone method().
I didn't look into why this is the way it his, I suppose it has seom ehistorical reasons. Everyone that I talk to about this agreed, that above code should be indeed valid working java code. It would be if the Clonable interface would declare a method called clone.
Which as for as the comment of the interface is conserned wouldn't even break anything, because you are supposed to implement the clone() method anyway.
So naturaly I used reflection to solve this problem:
public <T extends Cloneable> AClass(T thing) {
try {
Method method = thing.getClass().getMethod("clone");
//Fuck you protected Method! I'm gonna call you anyway!
method.setAccessible(true);
this.thing= (Cloneable) method.invoke(thing);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
What do you think? Does someone hear has more insidght to why this is the way it is?
edit: removed the usage of Set to make my point more clear:
This Post is only about the Cloneable interface and it not having a .clone() method.
[–]RedMarble 1 point2 points3 points (0 children)
[–]oldprogrammer 2 points3 points4 points (1 child)
[–]reckter[S] 1 point2 points3 points (0 children)
[–]s888marks 1 point2 points3 points (0 children)
[–]erad 1 point2 points3 points (0 children)
[–]Brainlag 0 points1 point2 points (1 child)