Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2007
    Posts
    1
    Rep Power
    0

    Question 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.

  2. #2
    sandeepkk2005 is offline Member
    Join Date
    Nov 2007
    Posts
    18
    Rep Power
    0

    Default

    Use
    Object temp= (Object)i;

  3. #3
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    757
    Rep Power
    8

    Default

    What if you get the class name using:

    Java Code:
    someObject.getClass().getName();
    or

    Java Code:
    someObject.getClass().getSimpleName();
    And then from the string name of the class you can cast the object into the object you wanted it to be.

Similar Threads

  1. Replies: 4
    Last Post: 03-25-2008, 12:16 PM
  2. String to Integer conversion
    By eva in forum New To Java
    Replies: 2
    Last Post: 12-17-2007, 03:59 PM
  3. Replies: 1
    Last Post: 08-02-2007, 04:07 PM
  4. How can I cast Object as an int
    By romina in forum New To Java
    Replies: 1
    Last Post: 07-18-2007, 11:20 AM
  5. Creating object of Type Object class
    By venkatv in forum New To Java
    Replies: 3
    Last Post: 07-17-2007, 03:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •