Java object get class type

How to Get Type of Object in Java?

An object is a physical entity that has its own state and behavior, and it acts as a unique instance of a Java class. It. When the object originates from a source, it is considered useful to examine the object type. Also, knowing the type of an object is crucial when working with a collection that includes different objects or when it is required to execute the logical operation with the same kind of variables.

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:

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.

Читайте также:  Как обновить версию php timeweb

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:

public class Example {
public static void main ( String [ ] args ) {
MyClass myclassObj = new MyClass ( ) ;
if ( myclassObj. getClass ( ) == MyClass. class ) {
System . out . println ( «The object ‘myclassObj’ is a type of ‘MyClass'» ) ;
} else if ( myclassObj. getClass ( ) == MynewClass. class ) {
System . out . println ( «The object ‘myclassObj’ is a type of ‘MynewClass'» ) ;
}
}
}

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:

public class Example {
public static void main ( String [ ] args ) {
MyClass myclassObj = new MyClass ( ) ;
if ( myclassObj instanceof MyClass ) {
System . out . println ( «The object ‘myclassObj’ is an instance of ‘MyClass'» ) ;
} else if ( myclassObj instanceof MynewClass ) {
System . out . println ( «The object ‘myclassObj’ is an instance of ‘MynewClass'» ) ;
}
}
}

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.

Источник

Retrieving Class Objects

The entry point for all reflection operations is java.lang.Class . With the exception of java.lang.reflect.ReflectPermission , none of the classes in java.lang.reflect have public constructors. To get to these classes, it is necessary to invoke appropriate methods on Class . There are several ways to get a Class depending on whether the code has access to an object, the name of class, a type, or an existing Class .

Object.getClass()

If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass() . Of course, this only works for reference types which all inherit from Object . Some examples follow.

Class c = System.console().getClass();

There is a unique console associated with the virtual machine which is returned by the static method System.console() . The value returned by getClass() is the Class corresponding to java.io.Console .

enum E < A, B >Class c = A.getClass();

A is an instance of the enum E ; thus getClass() returns the Class corresponding to the enumeration type E .

byte[] bytes = new byte[1024]; Class c = bytes.getClass();

Since arrays are Objects , it is also possible to invoke getClass() on an instance of an array. The returned Class corresponds to an array with component type byte .

import java.util.HashSet; import java.util.Set; Set s = new HashSet(); Class c = s.getClass();

In this case, java.util.Set is an interface to an object of type java.util.HashSet . The value returned by getClass() is the class corresponding to java.util.HashSet .

The .class Syntax

If the type is available but there is no instance then it is possible to obtain a Class by appending «.class» to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

boolean b; Class c = b.getClass(); // compile-time error Class c = boolean.class; // correct

Note that the statement boolean.getClass() would produce a compile-time error because a boolean is a primitive type and cannot be dereferenced. The .class syntax returns the Class corresponding to the type boolean .

Class c = java.io.PrintStream.class;

The variable c will be the Class corresponding to the type java.io.PrintStream .

The .class syntax may be used to retrieve a Class corresponding to a multi-dimensional array of a given type.

Class.forName()

If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName() . This cannot be used for primitive types. The syntax for names of array classes is described by Class.getName() . This syntax is applicable to references and primitive types.

Class c = Class.forName("com.duke.MyLocaleServiceProvider");

This statement will create a class from the given fully-qualified name.

Class cDoubleArray = Class.forName("[D"); Class cStringArray = Class.forName("[[Ljava.lang.String;");

The variable cDoubleArray will contain the Class corresponding to an array of primitive type double (that is, the same as double[].class ). The cStringArray variable will contain the Class corresponding to a two-dimensional array of String (that is, identical to String[][].class ).

TYPE Field for Primitive Type Wrappers

The .class syntax is a more convenient and the preferred way to obtain the Class for a primitive type; however there is another way to acquire the Class . Each of the primitive types and void has a wrapper class in java.lang that is used for boxing of primitive types to reference types. Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped.

There is a class java.lang.Double which is used to wrap the primitive type double whenever an Object is required. The value of Double.TYPE is identical to that of double.class .

Void.TYPE is identical to void.class .

Methods that Return Classes

There are several Reflection APIs which return classes but these may only be accessed if a Class has already been obtained either directly or indirectly.

Class.getSuperclass() Returns the super class for the given class.

Class c = javax.swing.JButton.class.getSuperclass();

The super class of javax.swing.JButton is javax.swing.AbstractButton . Class.getClasses() Returns all the public classes, interfaces, and enums that are members of the class including inherited members.

Class[] c = Character.class.getClasses();

Character contains two member classes Character.Subset and Character.UnicodeBlock . Class.getDeclaredClasses() Returns all of the classes interfaces, and enums that are explicitly declared in this class.

Class[] c = Character.class.getDeclaredClasses();
import java.lang.reflect.Field; Field f = System.class.getField("out"); Class c = f.getDeclaringClass();
public class MyClass < static Object o = new Object() < public void m() <>>; static Class = o.getClass().getEnclosingClass(); >

The declaring class of the anonymous class defined by o is null . Class.getEnclosingClass() Returns the immediately enclosing class of the class.

Class c = Thread.State.class().getEnclosingClass();
public class MyClass < static Object o = new Object() < public void m() <>>; static Class = o.getClass().getEnclosingClass(); >

Источник

Оцените статью