Runtime Type Identification in Java can be defined as determining the type of an object at runtime. It is extremely essential to determine the type for a method that accepts the parameter of type java.lang. Unlike C++ Java does not support Runtime Type Identification (RTTI) but it provides few methods to find objects at runtime.
Some essential points regarding Runtime Type Identification in Java are following:
- Determining the type of object at run time not only reduces error but also results in robustness.
- It is also useful before typecasting any object into another type to avoid run time exception.
- It is used to implement the type-specific feature on methods that accept types like objects or any interfaces.
The java.lang.Object.getClass() method is used to determine the type of object at run time.
Syntax:
public final Class getClass()
Return Type: Returns the Class objects that represent the runtime class of this object.
Example 1:
Java
// Java Program to determine Runtime type   import java.io.*;   public class Example1 {     public static void main(String[] args)     {         // Creating the obj         Object obj = new String( "Learn_programming" );           Class abc = obj.getClass();           // Print the class of obj         System.out.println( "Class of Object obj is : "                            + abc.getName());     } } |
Class of Object obj is : java.lang.String
Example 2:
Java
// Java program to determine object class at run time   import java.io.*;   public class Example2 {      public static void main(String[] args)       {         // create a new Integer       Integer num = new Integer( 100 );         // print num       System.out.println( "" + num);         // print the class of num       System.out.println( "" + num.getClass());       }   }  |
Output:
100 class java.lang.Integer