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?
source to share
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));
source to share