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

2013/1/4

Variable construction of Objects

JimmyFake JimmyFake

2013/1/4

#
Hi :) I want to create objects dependent on a variable. Example-Method: public Object createObject( object) { newObject = new object; return newObject; } I looked up the command for creating an object in the world class: Example: Wall wall = new Wall(); But I can't simply write new (); or something like this, and I'm out of ideas. Any help would be appreciated :) Thank you ;)
danpost danpost

2013/1/4

#
Would this be what you mean:
public Actor createObject(int var)
{
    Actor actor = null;
    if (var == 0) actor = new Wall();
    if (var == 1) actor = new Block();
    // etc.
    return actor;
}
JimmyFake JimmyFake

2013/1/4

#
thank you for the fast reply. It's not quite what i mean. Is there a way to do this with names(Strings) instead of Numbers. Like createObject(wall) or createObject(block) .... ?
danpost danpost

2013/1/4

#
How about this:
public Actor createObject(String objName)
{
    Actor actor = null;
    if ("wall".equals(objName)) actor = new Wall();
    if ("block".equals(objName)) actor = new Block();
    // etc.
    return actor
}
JimmyFake JimmyFake

2013/1/5

#
That's better thank you. But this would require me to write an oneline-code for every Class, that I want to be able to create objects from, with help of this method. And that would mean that everytime I add a new class, I need to edit this method, so it will be able to create objects from this class. Is there a way to make it completely generic? ( I hope you do understand what I mean, because I had difficulties to make myself clear) Thank you
danpost danpost

2013/1/5

#
I do understand what you mean, however, unless you are well versed at programming with java, any alternative would be difficult and probably require more code than what would be required with the one-liners.
JimmyFake JimmyFake

2013/1/5

#
okay, I'll trust you in that matter, and take the variant you showed me last. Thank you for the help :)
danpost danpost

2013/1/5

#
If you want any insight into it, it involved working with the 'Class' API using the 'newInstance' method which will require some knowledge of working with exceptions. It would be something like the following:
// call with
Actor actor = createActor(ClassName.class);
if(actor != null) ...

// with the method
public Actor createActor(Class cls)
{
    Actor actor = null;
    try { actor = (Actor) cls.newInstance(); }
    catch(Exception e) { }
    return actor;
}
However, this would require passing classes instead of strings.
You need to login to post a reply.