writing a method containsInstanceOf(Class<? extends SuperClassName>)

Simon Janssens :

I have written a class Couple

I want to write a method containsInstanceOf like this in (1), but I get the error "can't resolve cls to a type" I've solved it by using (2).

but I don't like it at all. do you have any suggestions on writing this method more elegant and failsafe ?

(1)

    private boolean containsInstanceof(Class<?extends GameObject> cls) {
    return this.getFirst() instanceof cls || this.getSecond() instanceof cls;
}

(2)

    private boolean containsInstanceof(Class<?extends GameObject> cls) {
    return this.getFirst().getClass().getName().equals(cls.getName()) ||
           this.getSecond().getClass().getName().equals(cls.getName());
}

expected no errors in (1) but get that cls can't be resolved to a type.

Andy Turner :

You have to use the Class.isInstance method:

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

return cls.isInstance(this.getFirst()) || cls.isInstance(this.getSecond());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115720&siteId=1