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

2012/6/19

Passing a class as a parameter

darkmist255 darkmist255

2012/6/19

#
Is something along these lines possible:
public void Method(Class passedClass)
{
    addObject(new passedClass, 50, 50);
}
^^ I know this is impossible, but the idea is that I would like to create a new instance from the class that has been passed.
Builderboy2005 Builderboy2005

2012/6/19

#
That is actually very close, and very possible. Try this:
public void Method(Class passedClass)
{
    addObject(passedClass.newInstance() , 50 , 50);
}
and you might also be interested in checking out the Documentation of the the Class
darkmist255 darkmist255

2012/6/19

#
You've got to be kidding me, I was trying to play around with "newInstance()" but never thought to actually run it from the wanted class itself =D. Thanks!
darkmist255 darkmist255

2012/6/19

#
Alright another question, is it possible to have an array of classes? The idea here is I want to have an array of Strings and an array of the Classes that they represent. For example:
    String[] tileTypes = {"TILE_grass"};
    class[] tileClasses = {TILE_grass.class};
...

//String "TILE_grass" has been passed as a parameter

addObject(tileClasses[Arrays.asList(tileTypes).indexOf(tileType)].newInstance(), 50, 50);
Unfortunately I can't seem to make an array of classes, is there a way this could be achieved?
Well... I can make an array of classes if I capitalize Class... Should be good now?
You need to login to post a reply.