简体   繁体   中英

Java - Class.isInstance() always returns false

In my GameObject class I have the following method to check if the GameObject would be colliding with another object if it moved to the specified position:

public boolean collisionAt(Vector2d position, Class<? extends GameObject>... exclusions) {
    if (getBounds() == null)
        return false;
    Rectangle newBounds = getBounds().clone();
    newBounds.setPosition(position);
    // Check collisions
    for (GameObject object : new ArrayList<>(gameObjects)) {
        if (object.getBounds() != null && newBounds.intersects(object.getBounds()) && object != this) {
            boolean b = true;
            for (Class<? extends GameObject> exclusion : exclusions) {
                if (object.getClass().isInstance(exclusion))
                    b = false;
            }
            if (b)
                return true;
        }
    }
    return false;
}

I want to allow the program to define exclusions, for example if I don't want this method to return true if it collides with a Spell. But for some reason the Class.isInstance() line always returns false. I even tried this:

System.out.println(Spell.class.isInstance(Spell.class));

and the console outputs false! What's going on here?

The isInstance tests if the given object is an instance of the Class , not if the given Class is a subclass of the Class .

You have your invocation backwards. You need to test if the gameObject is an instance of one of the exclusion classes.

if (exclusion.isInstance(gameObject))

From official Javadocs

public boolean isInstance(Object obj)

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

You need to pass in the object of class rather than the class itself.

Example

SomeClass object = new SomeClass();
System.out.println(SomeClass.class.isInstance(object));

You need to pass in an instance of the class in question rather than a class literal. Eg

Spell spell = new Spell();
System.out.println(Spell.class.isInstance(spell));

isInstance determines if the specified Object is assignment-compatible with the object represented by this Class . You're passing it a class when it expects an object.

The opposite should work:

Spell.class.isInstance(spell)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM