Java 中是否有类似 instanceOf(Class<?> c) 的东西? [英] Is there something like instanceOf(Class<?> c) in Java?
问题描述
我想检查对象 o
是 C
类的实例还是 C
的子类的实例.
I want to check if an object o
is an instance of the class C
or of a subclass of C
.
例如,如果 p
属于 Point
类,我希望 x.instanceOf(Point.class)
为 true
和 x.instanceOf(Object.class)
为 true
.
For instance, if p
is of class Point
I want x.instanceOf(Point.class)
to be true
and also x.instanceOf(Object.class)
to be true
.
我希望它也适用于盒装原始类型.例如,如果 x
是 Integer
那么 x.instanceOf(Integer.class)
应该是 true
.
I want it to work also for boxed primitive types. For instance, if x
is an Integer
then x.instanceOf(Integer.class)
should be true
.
有这种事吗?如果没有,我该如何实现这样的方法?
Is there such a thing? If not, how can I implement such a method?
推荐答案
Class.isInstance 做你想做的事.
if (Point.class.isInstance(someObj)){
...
}
当然,如果可以使用 instanceof
代替,则不应该使用它,但是对于反射场景,它通常会派上用场.
Of course, you shouldn't use it if you could use instanceof
instead, but for reflection scenarios it often comes in handy.
这篇关于Java 中是否有类似 instanceOf(Class<?> c) 的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!