Skip to content
Related Articles

Related Articles

Runtime Type Identification in Java
  • Difficulty Level : Medium
  • Last Updated : 22 Feb, 2021

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());
    }
}
Output
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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :