Re: super.clone() puzzlement
- From: Tom Anderson <twic@xxxxxxxxxxxxxxx>
- Date: Thu, 20 Nov 2008 21:40:07 +0000
On Thu, 20 Nov 2008, Derek Fountain wrote:
Generally, a copy constructor is more useful and less prone to mistakes.
public class MyClass {
public MyClass( MyClass mine ) {
//... make new class from old one...
}
}
I have a class like this:
class MyClass {
Object value;
// Implementation...
}
I want a copy of the MyClass instance where value references a deep copy of the value Object. That is, I want a copy of the MyClass instance where, when I change the object referenced by its value, a copy I've made of the MyClass instance keeps its own value object intact.
Am I right in thinking that given that I don't know what sort of Object value actually is, I've no way of reliably making a copy of it? Either with clone or a copy constructor or any other technique?
I guess I could change it to this:
class MyClass {
Cloneable value;
}
which would at least ensure the value was cloneable. But since I don't want to restrict what the user can store in value, I'm going to have to forego giving them a copy facility aren't I?
Probably.
Do the values have to be arbitrary objects, so could be a string, date, list, etc?
You might be able to do it if you define a sort of ValueCopier interface, and then find a convenient way to plug it in. Something like:
interface ValueCopier<T> {
public T copy(T obj) ;
}
class MyClass<T> {
private T value ;
private ValueCopier<T> copier ;
public MyClass(T value, ValueCopier<T> copier) {
this.value = value ;
this.copier = copier ;
}
public MyClass (MyClass<T> other) {
this.value = other.copier.copy(other.value) ;
this.copier = other.copier ;
}
}
You'd have to write a copier for each kind of thing you wanted to use as a value.
You might be able to use a static, global registry of copiers, organised as a map by class, to avoid having to fiddle around with copiers on a per-instance basis. That's a bit of a smelly solution, though.
tom
--
Also, a 'dark future where there is only war!' ... have you seen the
news lately? -- applez
.
- References:
- super.clone() puzzlement
- From: Derek Fountain
- Re: super.clone() puzzlement
- From: Mark Space
- Re: super.clone() puzzlement
- From: Derek Fountain
- super.clone() puzzlement
- Prev by Date: Re: Matrix performance question
- Next by Date: Re: How do i convert Java .class fine into .exe file!
- Previous by thread: Re: super.clone() puzzlement
- Next by thread: Re: super.clone() puzzlement
- Index(es):
Relevant Pages
|