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

2012/4/10

Level Saving - String to Object

Razzo Razzo

2012/4/10

#
Okay I've almost finished my level saving. I just need an Efficient way to convert a String (the name of the class) to Class.. For example. I have a class called Tree I have a string "Tree" I want to do addObject(new , x, y); How would I do this?
davmac davmac

2012/4/10

#
Your best bet is probably to do a big if-elseif block:
Actor newActor = null;
if (className.equals("Tree")) {
    newActor = new Tree();
}
else if (className.equals("Rock")) {
    newActor = new Rock();
}
addObject(newActor, x, y);
Razzo Razzo

2012/4/10

#
Awh! I was hoping there would be some Java black magic for it. I was going to do a Switch statement, but, You can't do it with strings for the version i'm using. If statements it is then!
danpost danpost

2012/4/11

#
You could actually use a 'switch' if you concatenate your class names with
switch ("WombatLeafTreeRockManFrog".indexOf("Tree"))
{
    case 0: addObject(new Wombat(), ...); break;
    case 6: addObject(new Leaf(), ...); break;
    case 10: addObject(new Tree(), ...); break;
    // etc.
}
danpost danpost

2012/4/11

#
Or, if you want to be more explicit:
String className = "Tree"; // actually gotten from saved data
switch ("Wombat Leaf Treefrog Rock Man Tree".indexOf(className + " "))
to avoid 'Tree' from producing 'Treefrog'.
You need to login to post a reply.