This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: How do I get the class of an object?

If class B and C both inherit from class A. Now THAT I have an object of type B or C, how do I determine what class of object this instance is.

Answer a

  1. Direct judgment type
if (obj instanceof C) {
//your code
}
Copy the code
  1. Gets the class of the object
 Object.getClass()
Copy the code

Answer two

There are a lot of ideas out there, but there are more:

  • Class.isAssignableFrom()
  • A simple attempt to cast an object may throwClassCastExceptionerror

I summarized all the methods available

Let’s test a possible way to determine if Object obj is an instance of type C:

// Method #1
if (obj instanceof C)
    ;

// Method #2
if (C.class.isInstance(obj))
    ;

// Method #3
if (C.class.isAssignableFrom(obj.getClass()))
    ;

// Method #4
try {
    C c = (C) obj;
    // No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}

// Method #5
try {
    C c = C.class.cast(obj);
    // No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}
Copy the code

Different handling of NULL

In the first two methods, if obj is null, the expression evaluates to false (null is not an instance of any object, but can be cast to any type).

The third method obviously throws a NullPointerException.

Instead, methods 4 and 5 accept NULL, because NULL can be converted to any type!

Note: NULL is not an instance of any type, but it can be converted to any type.

Class.getname () should not be used to perform the is instance of test, because an object that is not of type C but is a subclass of it may have a completely different name and package name, but it is still of type C.

Answer three

The big guys have come up with a lot of approaches, but I think the problem is due to OOP’s stinky design.

If your code is well designed, you probably don’t need to use getClass() or Instanceof

Any of the suggested methods will do, but remember that design matters too.

The article translated from Stack Overflow:stackoverflow.com/questions/5…