写一个方法 containsInstanceOf(Class<? extends SuperClassName>)

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

我写了一个class情侣

我想在 (1) 中写一个这样的方法 containsInstanceOf, 但是我收到错误 "can't resolve cls to a type" 我已经使用 (2).

解决了它

但我一点也不喜欢。您对将此方法编写得更优雅和故障安全有什么建议吗?

(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());
}

预期 (1) 中没有错误,但发现 cls 无法解析为类型。

你必须使用Class.isInstance方法:

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

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