检查对象是否属于 Java 中的类

是否有一种简单的方法来验证一个对象是否属于给定的类

if(a.getClass() = (new MyClass()).getClass())
{
//do something
}

但是这需要每次动态地实例化一个新对象,只是为了丢弃它。有没有更好的方法来检查“ a”是否属于“ MyClass”类?

202065 次浏览

Try operator instanceof.

Use the instanceof operator:

if(a instanceof MyClass)
{
//do something
}

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.

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.

So for example:

if (a.getClass() == X.class) {
// do something
}

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.

In comparison:

if (a instanceof X) {
// do something
}

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.

Most of the time, instanceof is right.

If you ever need to do this dynamically, you can use the following:

boolean isInstance(Object object, Class<?> type) {
return type.isInstance(object);
}

You can get an instance of java.lang.Class by calling the instance method Object::getClass on any object (returns the Class which that object is an instance of), or you can use class literals (for example, String.class, List.class, int[].class). There are other ways as well, through the reflection API (which Class itself is the entry point for).

I agree with the use of instanceof already mentioned.

An additional benefit of using instanceof is that when used with a null reference instanceof of will return false, while a.getClass() would throw a NullPointerException.

The usual way would be:

if (a instanceof A)

However, there are cases when you can't do this, such as when A in a generic argument.

Due to Java's type erasure, the following won't compile:

<A> boolean someMethod(Object a) {
if (a instanceof A)
...
}

and the following won't work (and will produce an unchecked cast warning):

<A> void someMethod(Object a) {
try {
A casted = (A)a;
} catch (ClassCastException e) {
...
}
}

You can't cast to A at runtime, because at runtime, A is essentially Object.

The solutions to such cases is to use a Class instead of the generic argument:

void someMethod(Object a, Class<A> aClass) {
if (aClass.isInstance(a)) {
A casted = aClass.cast(a);
...
}
}

You can then call the method as:

someMethod(myInstance, MyClass.class);
someMethod(myInstance, OtherClass.class);