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

2013/12/6

using a class parameter with setWorld() method

jkc1113 jkc1113

2013/12/6

#
Here is my code... public void nextLevel(Class x, Class y) { if (getOneIntersectingObject(x) != null) { Greenfoot.setWorld(new y); } } im trying to create this so that i dont have to individualy set the world to a new one for each of my end of level flags... the 5th line where it sais Greenfoot.setWorld(new y); does not work i have also tried (new y()) but neither work
jkc1113 jkc1113

2013/12/6

#
heres the code embedded if its easier to understand
public void nextLevel(Class x, Class y)
    {
        if (getOneIntersectingObject(x) != null)
        {
            Greenfoot.setWorld(new y);
        }
    }
davmac davmac

2013/12/6

#
Really, you should use the factory pattern and pass in a factory instance instead of a class. However, this also works: replace line 05 above with the following lines:
           try {
                Greenfoot.setWorld(y.newInstance());
            }
            catch (InstantiationException ie) {
                throw new RuntimeException(ie);
            }
            catch (IllegalAccessException iae) {
                throw new RuntimeException(iae);
            }
As you can see it is a bit messy, largely due to the need to catch exceptions. Also, it uses reflection, which you should avoid where possible.
You need to login to post a reply.