Java中有类似instanceOf(Class<?> c)的东西吗? [英] Is there something like instanceOf(Class<?> c) in Java?
问题描述
我想检查对象 o
是否是类 C
或<的子类的实例code> 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屋!