Java - Class.isInstance () always returns false

In my GameObject class, I have the following method to check if the GameObject will collide with another object if it moves to a 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 exceptions, for example if I don't want this method to return true if it encounters a spell. But for some reason the line Class.isInstance () always returns false. I even tried this:

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

      

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

+3


source to share


3 answers


isInstance

checks if the given object is an instance Class

, not if the given one Class

is a subclass Class

.

You have your call back. You need to check if an gameObject

instance of one of the exception classes is.



if (exclusion.isInstance(gameObject))

      

+4


source


From the official Javadocs

public boolean isInstance(Object obj)

      

Determines whether the specified object is compatible with an object represented by this class. This method is the dynamic equivalent of the Java language instance operator. The method returns true if the specified Object argument is non-null and can be passed to the reference type represented by this class object without raising the ClassCastException class. Otherwise, it returns false.



You need to pass the class object, not the class itself.

Example

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

      

+5


source


You need to pass in an instance of the class in question, not a class literal. For example.

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

      

+2


source







All Articles