This site requires JavaScript, please enable it in your browser!
Greenfoot back
K_O_P
K_O_P wrote ...

2012/2/10

Copy an Object

K_O_P K_O_P

2012/2/10

#
I've got a problem... I want to copy any object.... So that I've got two Objects of the same class... How can I manage it, without knowing before, which class it is?
sp33dy sp33dy

2012/2/10

#
If I understand you correctly, you'll need your code to figure out the type and then instantiate a new one. One option is to use instanceOf, i.e:
if (thisObject isInstanceof Class) {
  Class newX = new Class();
}
In the above code, thisObject would be your object variable and Class would be which ever class 'it' might be. The second problem you'll face is making a copy of your first Class. Depending on what type of data you have in it, you may or may not need a 'copy' method rather than just assigning one object into the other. I.E. newX = thisObject will not make a copy but a reference to the first; therefore changing a value in one will be effectively duplicated in the other. It is also possible to use reflection to create the class, but you need to google that; as it is way beyond the normal skill level here (in my opinion).
K_O_P K_O_P

2012/2/10

#
I know, what you mean! But what I mean is, to to copy an object with all the variables values... and without checking 100 Classes, till I've got it
Busch2207 Busch2207

2012/2/10

#
Mabye try to use an interface class, where is a method, that returns a copy of each Object
public interface Copy
{
    Copy duplicate();
}
and in the classes, that should be able to be copied:
public class Example extends Actor implements Copy
{
    private String ExampleName;
    [...]

    public Copy duplicate()
    {
        Example Exe = new Example();
        Exe.ExampleName = this.ExampleName;
        [...]
        return Exe;
    }
}
And the you can use the "duplicate" - Method, if you have a reference to an Object of the class Copy. For example:
    public Copy getACopyOfTheObject(Copy ObjectToCopy)
    {
        return ObjectToCopy.duplicate();
    }
You need to login to post a reply.