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

Arc*_*ica 1 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;
}
Run Code Online (Sandbox Code Playgroud)

我不能理解的是,如何通过像BouncyBallcollidesWith().理想情况下,我不想为每次调用创建一个实例collidesWith(),但如果我绝对必须,我可以使用它.

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

  • 是否适合使用 instanceof
  • 我是否想要通过课程
  • 我是否真的想通过课程

我需要使用反射吗?我必须得到班级的名字并与之比较equals()吗?是否需要创建实例?

JB *_*zet 5

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

if(gameObjects[i] instanceof BouncingBall) {
Run Code Online (Sandbox Code Playgroud)

由于您希望它是动态的,因此必须使用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;
}
Run Code Online (Sandbox Code Playgroud)

你可以使用例如调用方法:

collidesWith(caller, BouncingBall.class)
Run Code Online (Sandbox Code Playgroud)