How to determine an object's class?
If class B and class C extend class A and I have an object of type B or C , how can I determine of which type it is an instance?
![]()
13 Answers 13
Use Object.getClass . It returns the runtime type of the object. Here’s how to call it using your example:
You can also compare two Class instances to see if two objects are the same type.
Multiple right answers were presented, but there are still more methods: Class.isAssignableFrom() and simply attempting to cast the object (which might throw a ClassCastException ).
Possible ways summarized
Let’s summarize the possible ways to test if an object obj is an instance of type C :
Differences in null handling
There is a difference in null handling though:
- In the first 2 methods expressions evaluate to false if obj is null ( null is not instance of anything).
- The 3rd method would throw a NullPointerException obviously.
- The 4th and 5th methods on the contrary accept null because null can be cast to any type!
To remember: null is not an instance of any type but it can be cast to any type.
Получить тип объекта в Java

В этой статье мы узнаем, как получить тип объекта в Java. Если объект поступает из источника, полезно проверить тип объекта. Это место, где мы не можем проверить тип объектов, например из API или частного класса, к которому у нас нет доступа.
Получить тип объекта с помощью getClass() в Java
В первом методе мы проверяем тип Object классов-оболочек, таких как Integer и String . У нас есть два объекта, var1 и var2 , для проверки типа. Мы воспользуемся методом getClass() класса Object , родительского класса всех объектов в Java.
Проверяем класс по условию если . Поскольку классы-оболочки также содержат класс поля, возвращающий тип, мы можем проверить, чей тип совпадает с var1 и var2 . Ниже мы проверяем оба объекта трех типов.
Получить тип объекта с помощью instanceOf в Java
Другой способ получить тип объекта в Java — использовать функцию instanceOf ; он возвращается, если экземпляр объекта совпадает с заданным классом. В этом примере у нас есть объекты var1 и var2 , которые проверяются с этими тремя типами: Integer , String и Double ; если какое-либо из условий выполняется, мы можем выполнить другой код.
Поскольку var1 имеет тип Integer , условие var1 instanceOf Integer станет истинным, а var2 — Double , так что var2 instanceOf Double станет истинным.
Please enable JavaScript
Получить тип объекта класса, созданного вручную в Java
Мы проверили типы классов-оболочек, но в этом примере мы получаем тип трех объектов трех созданных вручную классов. Мы создаем три класса: ObjectType2 , ObjectType3 и ObjectType4 .
ObjectType3 наследует ObjectType4, а ObjectType2 наследует ObjectType3. Теперь мы хотим узнать тип объектов всех этих классов. У нас есть три объекта: obj , obj2 и obj3 ; мы используем оба метода, которые мы обсуждали в приведенных выше примерах: getClass () и instanceOf.
Однако есть отличия между типом obj2 . Переменная obj2 вернула тип ObjectType4 , а ее класс — ObjectType3 . Это происходит потому, что мы наследуем класс ObjectType4 в ObjectType3 , а instanceOf проверяет все классы и подклассы. obj вернул ObjectType3 , потому что функция getClass() проверяет только прямой класс.
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Оператор instanceof . Определение типа объекта. Примеры
Оператор instanceof используется для определения типа объекта во время выполнения программы. Определив тип объекта можно реализовать корректное приведение типов в случае, когда классы образуют иерархию. Если выполнить некорректное приведение к некоторому типу, то на этапе выполнения будет сгенерирована исключительная ситуация, что неприемлемо.
Общая форма оператора instanceof следующая
- reference – ссылка на объект (экземляр) класса;
- type – тип класса.
Результатом работы оператора instanceof есть значение true или false . Результат true возвращается в случаях:
- если ссылка reference относится к указанному типу;
- если ссылка reference может быть приведена к указанному типу.
В других случаях возвращается значение false .
2. Применение instanceof для классов, образующих иерархию. Пример
В примере демонстрируется корректное определение типа, к которому принадлежит объект класса. Реализовано два класса A и B , которые образуют иерархию. С целью демонстрации определяется тип соответствующего объекта с учетом того, что унаследованный класс расширяет возможности суперкласса.
Результат выполнения программы
Как видно из результата, экземпляр унаследованного класса B может быть корректно приведен к суперклассу A . А вот экземпляр суперкласса A не может быть расширен к возможностям унаследованного класса B .
3. Применение instanceof для типа Object . Пример
В объектной модели языка Java все создаваемые классы унаследованы от класса Object . В следующем примере приходится это утверждение.
Результат работы программы
4. Применение instanceof для ссылки на базовый класс. Пример
Если классы образуют иерархию наследования, то ссылка на суперкласс может получать значение экземпляров любого производного класса. В примере ниже демонстрируется определение того, может ли ссылка на суперкласс быть приведена к типу производного класса.
How to Get Type of Object in Java?
This article will help you to learn the method to get the type of an object in Java.
How to Get Type of Object in Java?
For getting the type of predefined or user-defined class object in Java, you can use:
- getClass() method
- instanceof operator
We will now check out each of the mentioned methods one by one!
Method 1: Get Type of Pre-defined Class Object Using getClass() Method
In Java, we have predefined classes like wrapper classes such as String, Double, Integer, and many more. Sometimes we need to verify the object type while using predefined classes. For this purpose, Java offers a “getClass()” method that belongs to the “Object” class.
Syntax
The syntax of the “getClass()” method is given as follows:
Here, the “getClass()” method will return the class of the specified “x” object.
Example
In this example, we will create a String type object named “x” containing the following value:
Next, we will print a statement using the “System.out.println()” method:
Lastly, we will get the type of the object “x” by calling the “getClass()” method:
The output shows that the created variable belongs to the Java String class:

Let’s see another method to get the object type using the “instanceof” operator.

Method 2: Get Type of Pre-defined Class Object Using “instanceof” Operator
You can also utilize the “instanceof” operator to check the object type in a Java program. This operator returns a boolean value which indicates whether the object is an instance of the particular class or not.
Syntax
The syntax of the “instanceof” is as follows:
Here, “x” is an object and “Integer” is the predefined Java wrapper class. The “instanceof” operator checks whether the object belongs to the mentioned class or not and returns a boolean value.
Example
In this example, we have an object “x” of the Integer class having “5” as its value:
Next, we will print a statement using the “System.out.println()” method:
Now, we will check whether the object is an instance of an Integer class or not:

The output displayed “true” as the object “x” is an instance of the Integer class:

At this point, you may be wondering about how to get the type of user-defined class object. The below-given section will assist you in this regard.
Method 3: Get Type of User-defined Class Object Using getClass() Method
You can also get the type of the user-defined class object with the help of the “getClass()” method. In such a scenario, we will compare the object with the class name using the “==” comparison operator.
Syntax
For the specified purpose, the syntax of “getClass()” method is given as:
Here, the “getClass()” method is called by the “myclassObj” object of the “MyClass” and then compared with the name using the comparison operator “==”.
Example
In this example, we have three classes named “MyClass”, “MynewClass”, and “Example”, where MyClass acts as a parent class of MynewClass:
The “MynewClass” is a child class as it is extended from “MyClass”:
In the main() method of the class “Example”, we will declare and instantiate an object of the parent class “MyClass”. Then check whether the created object belongs to which class; parent or child? To do so, we will call the “getClass()” method with the created object and compare the resultant value with parent and child class names using if-else-if conditions:

The output indicates that the object “myclassObj” belongs to the parent class named “MyClass”:

Now, head toward the next section!
Method 4: Get Type of User-defined Class Object Using “instanceof” Operator
Similar to predefined classes, for user-defined classes, you can also get the type of object by using the “instanceof” operator.
Syntax
The syntax is given below:
Here, the “instanceof” operator will check if the “myclassObj” is an instance of “MyClass” or not.
Example
We will now utilize the same classes which we have created in the previously mentioned example. The only difference is that we will use the “instanceof” operator to verify if the created object instance belongs to the parent or child class:
The given output shows that the “instanceof” operator validated the type of the object as “MyClass”:

We have compiled all methods related to getting object type in Java.

Conclusion
To get a type of object in Java, you can use the “getClass()” method or the “instanceof” operator. These methods can be used to check object types for both predefined and user-defined classes. The getClass() method returns the class name while the “instanceof” operator returns a boolean value, where “true” indicates the object belongs to that specified class; otherwise, it returns “false”. This article provided all the methods to get the object type in Java.
About the author

Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.