I have a method, that accepts as parameter all classes that extend Persona.Class
(Uomo.Class
and Donna.Class
extend Persona.Class
).
public PersonaDecorator(Class <? extends Persona> persona) {
}
Inside this method, I need to know if the class sent to the method is Uomo.Class
or Donna.Class
.
I Thought I could do something like this:
public PersonaDecorator(Class <? extends Persona> persona) {
if(persona instanceof Uomo){
......
}
}
But I get this error: Incompatible conditional operand types Class<capture#1-of ? extends Persona> and Uomo
Thank you
The instanceof
operator tests whether a reference (the left operand) refers to an object which is an instance of the class named on the right operand.
Here, persona
will be a reference to an instance of Class
, and an instance of Class
can never be an instance of Persona
. You're testing for an impossible condition, and the compiler is helpfully telling you about that mistake.
I suspect you want Class.isAssignableFrom
:
if (Uomo.class.isAssignableFrom(persona))
That would find subclasses of Uomo
as well. If you want to test whether it's exactly the Uomo
class, you can just use:
if (persona == Uomo.class)
See more on this question at Stackoverflow