Java:在运行时将类作为参数传递

时间:2014-09-07 13:37:59

标签: java game-engine

我正在编写一种游戏引擎。我的所有对象都来自GameObject类。我需要能够检查对象是否正在触摸另一个对象,指定类型。因此我的代码是:

public boolean collidesWith(GameObject caller, Class collideType) {
    for( /* the array of all GameObjects */ ) {

        // only check against objects of type collideType
        // this line says "cannot find symbol: collideType"
        if(gameObjects[i] instanceof collideType) {
            // continue doing collision checks
            // return true in here somewhere
        }
        else continue;
    }
    return false;
}

我无法理解的是如何将BouncyBall传递给collidesWith()。理想情况下,我不想为collidesWith()的每次调用创建一个实例,但如果我绝对必须,我可以使用它。

这里有很多问题和答案都涉及愚蠢的事情:

  • 是否适合使用instanceof
  • 我是否想要传递课程
  • 是否想要传递课程

我需要使用反射吗?我必须获得该课程的名称并将其与equals()进行比较吗?是否需要创建实例?

1 个答案:

答案 0 :(得分:5)

instanceof运算符期望类的文字名称。例如:

if(gameObjects[i] instanceof BouncingBall) {

由于您希望它是动态的,因此必须使用Class.isInstance()方法,该方法检查其参数是否是调用该方法的Class对象的实例:

public boolean collidesWith(GameObject caller, Class<? extends GameObject> collideType) {
    for ( /* the array of all GameObjects */ ) {
        if(collideType.isInstance(gameObjects[i])) {
            // continue doing collision checks
            // return true in here somewhere
        }
        else continue;
    }
    return false;
}

您可以使用例如:

来调用该方法
collidesWith(caller, BouncingBall.class)