Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 278
carrier Avatar asked Feb 12 '09 15:02

carrier


People also ask

How do you find an object's class?

getClass() If an instance of an object is available, then the simplest way to get its Class is to invoke Object. getClass() .

How do you define an object class?

In computer programming, the object class refers to a class created to group various objects which are instances of that class. Classes are code templates for creating objects. In cases where objects need to be grouped in a certain way, an object class is the "container" for a set of objects built on these templates.

What method is used to determine the type of an object?

The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.

How to determine the class of an object in Java?

In this example, we will learn to determine the class of an object in Java using the getClass () method, instanceof operator, and the isInstance () method. To understand this example, you should have the knowledge of the following Java programming topics:

How to check if the object is an object of test?

Here, we have used the isInstance () method of the class Class to check if the object obj is an object of the class Test. The isInstance () method works similarly to the instanceof operator.

What is the difference between class and object?

An object is an instance of a class. When a class is created, no memory is allocated. Objects are allocated memory space whenever they are created. The class has to be declared only once. An object is created many times as per requirement. available in the memory.

How to check the class of an object at runtime?

This method will return true if our object sent as the method's argument passes the IS-A test for the class or interface type. We can use the isInstance () method to check the class of an object at runtime.


2 Answers

if (obj instanceof C) { //your code } 
like image 95
IAdapter Avatar answered Sep 28 '22 00:09

IAdapter


Use Object.getClass(). It returns the runtime type of the object.

like image 28
Bill the Lizard Avatar answered Sep 28 '22 00:09

Bill the Lizard