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


Using a variable in place of a class name in a method

FirewolfTheBrave FirewolfTheBrave


I'm trying to write a method that can quickly add a given amount of objects from a given class on random free spaces on the map. For this, I've come up with the following code:
public void place (int amount, Class objectType)
        for (int i = 0; i < amount; i++)
            objectType placeThis = new objectType;   //This is the problematic line
            int x, y;
            do {
                x = Greenfoot.getRandomNumber (getWidth());
                y = Greenfoot.getRandomNumber (getHeight());
            } while (getObjectsAt (x, y, Actor.class).size() != 0);
            addObject (placeThis, x, y);
The problem: The compiler won't accept "objectType" as a valid class for the new object, even though its type is Class. How can I fix this?
danpost danpost


One way to instantiate a class is something like this:
Actor placeThis = null;
try { placeThis = objectType.newInstance(); }
catch (Exception e) { break; }
This is to replace line 5. The break statement should exit the for loop should a problem arise during instantiation of the class.
FirewolfTheBrave FirewolfTheBrave


I did need to do an additional typecasting in your second line (bc Object != Actor), but overall, it worked. Thank you!
You need to login to post a reply.