Question

I have a condition -

public class A {}
public class B extends A {}
A a = new B();



boolean flag = a instanceof B; // returns true

public boolean isOfType(A a, Class<? extends A> type) {
    return (a instanceof type); // throws syntax error
}

I am very curious why the condition is throwing syntax error. Am I doing anything wrong here?

Was it helpful?

Solution

Yes, you should be using type.isInstance(a). instanceof is not for objects of type Class, but for class names, e.g. a instanceof String, not a instanceof String.class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top