Runtime Type Identification in Java
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
import java.io.*;
public class Example1 {
public static void main(String[] args)
{
Object obj = new String( "Learn_programming" );
Class abc = obj.getClass();
System.out.println( "Class of Object obj is : "
+ abc.getName());
}
}
|
Output
Class of Object obj is : java.lang.String
Example 2:
Java
import java.io.*;
public class Example2 {
public static void main(String[] args)
{
Integer num = new Integer( 100 );
System.out.println( "" + num);
System.out.println( "" + num.getClass());
}
}
|
Output:
100
class java.lang.Integer
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...