|
How to cast an Object into a specific type (Integer/String) at runtime
Problem:
How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
Example:
public class TestCode {
public static Object func1()
{
Integer i = new Integer(10); //or String str = new String("abc");
Object temp= i; //or Object temp= str;
return temp;
}
public static void func2(Integer param1)
{
//Performing some stuff
}
public static void main(String args[])
{
Object obj = func1();
//cast obj into Integer at run time
func2(Integer);
}
}
Description:
In example, func1() will be called first which will return an object. Returned object refer to an Integer object or an String object. Now at run time, I want to cast this object to the class its referring to (Integer or String).
For e.g., if returned object is referring to Integer then cast that object into Integer and call func2() by passing Integer object.
|