Check if an object belongs to a class in Java(检查一个对象是否属于Java中的一个类)
问题描述
有没有一种简单的方法来验证一个对象是否属于给定的类?例如,我可以这样做
Is there an easy way to verify that an object belongs to a given class? For example, I could do
if(a.getClass() = (new MyClass()).getClass())
{
//do something
}
但这需要每次都在运行中实例化一个新对象,只是为了丢弃它.有没有更好的方法来检查a"是否属于MyClass"类?
but this requires instantiating a new object on the fly each time, only to discard it. Is there a better way to check that "a" belongs to the class "MyClass"?
推荐答案
instanceof
关键字,如其他答案所述,通常是您想要的.请记住,instanceof
也会为超类返回 true
.
The instanceof
keyword, as described by the other answers, is usually what you would want.
Keep in mind that instanceof
will return true
for superclasses as well.
如果你想查看一个对象是否是一个类的直接实例,你可以比较这个类.您可以通过getClass()
获取实例的类对象.您可以通过 ClassName.class
静态访问特定的类.
If you want to see if an object is a direct instance of a class, you could compare the class. You can get the class object of an instance via getClass()
. And you can statically access a specific class via ClassName.class
.
例如:
if (a.getClass() == X.class) {
// do something
}
在上面的示例中,如果 a
是 X
的实例,则条件为真,但如果 a
是 a 的实例,则条件不成立X
的子类.
In the above example, the condition is true if a
is an instance of X
, but not if a
is an instance of a subclass of X
.
比较:
if (a instanceof X) {
// do something
}
在 instanceof
示例中,如果 a
是 X
的实例,或者 a
的实例,则条件为真> 是 X
的 子类 的一个实例.
In the instanceof
example, the condition is true if a
is an instance of X
, or if a
is an instance of a subclass of X
.
大多数时候,instanceof
是对的.
Most of the time, instanceof
is right.
这篇关于检查一个对象是否属于Java中的一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查一个对象是否属于Java中的一个类


基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01