Check if an object belongs to a class in Java [duplicate]
Is there an easy way to verify that an object belongs to a given class? For example, I could开发者_如何学Go do
if(a.getClass() = (new MyClass()).getClass())
{
//do something
}
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"?
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).
Use the instanceof
operator:
if(a instanceof MyClass)
{
//do something
}
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
.
Try operator instanceof
.
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);
精彩评论