1

I am trying to compare part with the c class given from the constructor but for some reason my IDE pops a warning that it will always be false.

Class<? extends Part> c;

public Slot(Class<? extends Part> c){
    this.c = c;
}

public boolean addItem(Part part){
    return part instanceof c;
}

Why is this instanceof statement always false and what is the correct syntax to compare part with c?

user36976
  • 322
  • 2
  • 10

3 Answers3

8

You should call the following Class method:

Class.isInstance(Object obj)

When you call "instanceof c", "c" should be a Class, not a variable. In your example, c is a variable whose type is Class.

Fabien Fleureau
  • 693
  • 5
  • 14
1

Instead of this

if(part instanceof c) return true;

Try this

if(c.isAssignableFrom(part.getClass())) return true;

This is different than Class.isInstance(Object), because isAssignableFrom also returns true when part is the same type as or a sub-class of c.

So if you need to know if this is the exact same type use isInstance, if it could also be a sub-class, then use isAssignableFrom.

Community
  • 1
  • 1
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
1

It's about understanding the operator instanceof and the Class class.

Type Comparison Operator instanceof:

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

This means that your code if (part instanceof c) ... will always return false, as part can never be cast to Class.

If you have a look at Class.inInstance(Object obj), you find that

This method is the dynamic equivalent of the Java language instanceof operator.

In other words:

  1. If you know the checked type in compile-time, you use instanceof.
  2. If you do not know the checked type in compile-time, but in run-time (so you have it stored in a variable of the Class type), you use Class.inInstance(Object obj).
Honza Zidek
  • 9,204
  • 4
  • 72
  • 118