检查对象是否属于Java中的类 [英] Check if an object belongs to a class in Java

查看:88
本文介绍了检查对象是否属于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 X <的子类的实例则不是/ code>。

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 是对的。

这篇关于检查对象是否属于Java中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆