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.

GDS123 wrote:
Problem:
How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
There is only one way to have an object of an unknown type at compile time. That is to create the object's class at runtime using a classloader. Typically a URLClassloader.
Look into
Class.ForName(String)

Similar Messages

  • How do I count objects of a specific type in a Vector? Java 1.3 source.

    How do I count the objects of a specific type in a Vector?

    isInstance may allow too much for your needs as it allows any object which can be typecast to 'type' while you seem to want to limit to objects which are exactly of the type 'type'. In such a case you could do this:
    for (Enumeration e = attachmentTypes.elements(); e.hasMoreElements();)
      Object check = e.nextElement();
      if (check.getClass().equals(type)) {
        counter++;
    }Javadoc of the isInstance() method:
    http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#isInstance%28java.lang.Object%29
    (I link to the old Javadoc given you mentioned Java 1.3 compatible source)

  • How To Insert A object into Conext

    Hi Techies,
    I have 8 tables in my designer
    and I have two contexts at designer level
    And how to insert a object into a context that is not referencing any table.
    For Example I have an object like "rownum" (Which should must be added at Universe level only not at report level). Here this object is not referencing any table and I want this to be used in a query where the remaining objects are coming from the context..
    Thanks in Advance..

          Double-click the Objects and click the TABLES button and select the table you want to associate the object to for the context to work properly (see below).
    Regards,
    Ajay

  • How to convert Java Objects into xml?

    Hello Java Gurus
    how to convert Java Objects into xml? i heard xstream can be use for that but i am looking something which is good in performance.
    really need your help guys.
    thanks in advance.

    There are apparently a variety of Java/XML bindings. Try Google.
    And don't be so demanding.

  • How to cast an int into an Object?

    If I want to push the int called result (e.g. result = 3 + 4) on my Stack, it doesn't work, because push asks for an Object.
    So how can I cast my int into an Object?
    Thanks for help!
    trampoline

    All the primitive types have wrapper classes. In this case use the following:
    int result = 3+4;
    Integer iResult = new Integer(result);
    Now push iResult onto your stack.

  • How to cast an object in JSF?

    I am working on a travel application. A user can have several bookings and a booking can have several components. A component can be either air or hotel. I want to list the user's bookings on the client using JSF datatable.
    <h:dataTable var="component" value="#{booking.components}">
    Now depending upon the class of component I need to present different information.
    My question is how to cast the variable in JSF ?
    Thanks

    You can use the String value of Object#getClass()#getName() to lookup the classname and evaluate it in the 'rendered' attribute.
    Basic example:
    package mypackage;
    public class Animal {}
    package mypackage;
    public class Cat extends Animal {}
    package mypackage;
    public class Dog extends Animal {}
    package mypackage;
    public class Fish extends Animal {}MyBeanpublic List<Animal> getList() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(new Dog());
        animals.add(new Cat());
        animals.add(new Fish());
        return animals;
    }JSF<h:dataTable value="#{myBean.list}" var="item">
        <h:column>
            <h:outputText value="It's a Cat" rendered="#{item.class.name == 'mypackage.Cat'}" />
            <h:outputText value="It's a Dog" rendered="#{item.class.name == 'mypackage.Dog'}" />
            <h:outputText value="It's a Fish" rendered="#{item.class.name == 'mypackage.Fish'}" />
        </h:column>
    </h:dataTable>As far there is no way to cast objects in JSF.
    Edit
    If you find it useful, move the classname request to the superclass:
    public class Animal {
        public String getType() {
            String className = getClass().getName();
            return className.substring(className.lastIndexOf('.') + 1);
    }Which makes life easier without struggling with package names:<h:outputText value="It's a Cat" rendered="#{item.type == 'Cat'}" />
    <h:outputText value="It's a Dog" rendered="#{item.type == 'Dog'}" />
    <h:outputText value="It's a Fish" rendered="#{item.type == 'Fish'}" />Message was edited by:
    BalusC

  • How to impdp data only into a specific schema

    Hello,
    How to impdp Tables and Materialized Views only into a specific schema. Also, how to exclude certain tables in particular schemas from being imported. Thank you.

    Pl Check the link
    http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14215/dp_import.htm#i1007865
    Thanks

  • How to write the errors into a specific file

    Hi all,
    How to handled the errors in the scenarios,By using fault messages we can informed about errors to sender.But in my case i have to gather all errors & write into a specific file.For this can i create another Communication Channel for File reciever.How can i gather error messages in the scenario.
    Early response is appreciate

    Hi,
    Bhavesh had already answered how to handle it. For saving it in a file yes you can use File Receiver adapter.
    Regards,
    Prakash

  • How to convert the Object into tonumber

    Hi all,
    How to convert a date in Object type into a number type.
    eg:
    Object EVENT_NUMBER = ADFContext.getCurrent().getSessionScope().get("SV_EVENT_NUMBER");
    Number LV_N_EVENT_NUMBER = EVENT_NUMBER.*toNumber();*
    I need to assign the value in number type to variable LV_N_EVENT_NUMBER.
    Thanks in advance
    C.Karukkuvel

    Hi,
    I am assuming you are using oracle.jbo.domain.Number.
    Is this what you need?
    Number num;
                try {
                    num = new Number(object);
                } catch (SQLException e) {
                }Gabriel.

  • How to get mail address into a specific address group folder

    I need to be able to copy an email address from Mail and when saving it into Address Book, have it automatically go into a specific folder.
    Seems pretty obvious but I'm not seeing how to do this.
    Or is my only option to save to Address Book then manually drag the address into the intended folder?
    Thanks.

    Mail will only add an address to the main Address Book list. You could write an Applescript to perform the operation or possibly an Automator script.

  • How can I import photos into a specific album?

    Wow, I have been using Applescript for 15 years but I can't get this to work. I just want to make a script that brings a JPG image into iPhoto '09 into a specific album, but it seems set against letting me, and I can't find specific examples of what I'm trying to do so far.
    tell application "iPhoto"
    new album name "hello"
    add "Mac HD:Users:pp:mypic.jpg" to album "hello"
    end tell
    This doesn't give an error and it makes the album, but nothing else. Nothing is imported into iPhoto.
    Eventually I want to add a title and keyword data to that picture also using Applescript (hopefully not UI scripting), but since I can't get the barest basics of importing to work properly, I thought I'd see if anyone here could help.

    Peter
    I’ve never seens an AS that can do this. Hazel can and it might be worth examining it to see what you can learn.
    Automator can do this too, but there’s no way in that to add keywords or titles in that - though it is possible with Aperture and Automator.
    Given that we can go months on here without mention of AppleScript I wouldn’t be surprised if you get a better response on the AppleScript forum.
    Regards
    TD

  • How to insert an object into an object array

    I have an array of objects and im trying to insert an object into the array at position zero. Does anyone know what method I can use for this?

    Hey,
    Are u using a normal array or an array list ?
    For instance if you are using a normal array and you wnat to store an object of classX it should be something like this:
      myArray[0] = new classX(vlaue1, Value2, Value3);this will only work if you have a default constructer for the objects.
    I am posting under correction here but this is the basic idea.
    Hope it helps :-)

  • How to convert an Object into integer?

    Ho can v convert an object of type Object into integer data type?
    Object obj = null;
    integer int = _____________;
    plz do fill it up and help ASAP......

    Fortunately, Gosling was able to predict that his
    language would produce exceptions, so he gave usthe
    catch block, so we can magically make them goaway:
    > catch (Exception exc) {}You are
    probably not without knowing that empty catch blocks
    are considered to be bad practice.
    You should better do the following
    :catch(Exception exc) {
    throw new RuntimeException();
    ode]You turned your sarcasm detector off or something?? :-)

  • How to block accounting by MIRO for specific type of documents.

    Hello
    Is there any possibility to block accounting by MIRO for specific type of document? So you could only account specific type of documents by FBV* or FB*.
    Regards
    Marcin Obukowicz

    Hi,
    You can try to make a validation (OB28) which will check the document type based on transaction code prerequisites.
    Regards,
    Eli

  • How to cast an object to a class known only at runtime

    I have a HashMap with key as a class name and value as the instance of that class. When I do a 'get' on it with the class name as the key, what I get back is a generic java.lang.Object. I want to cast this generic object to the class to which it belongs. But I don't know the class at compile time. It would be available only at runtime. And I need to invoke methods on the instance of this specifc class.
    I'm not aware of the ways to do it. Could anybody suggest/guide me how to do it? I would really appreciate.
    Thanks a lot in advance.

    Thanks all for the prompt replies. I am using
    reflection and so a generic object is fine, I guess.
    But a general question (curiosity) specific to your
    comment - extraordinarily generic...
    I understand there's definitely some overhead of
    reflection. So is it advisable to go for interface
    instead of reflection?
    Thanks.Arguments for interfaces rather than reflection...
    Major benefit at run-time:
    Invoking a method using reflection takes more than 20 times as long without using a JIT compiler (using the -Xint option of Java 1.3.0 on WinNT)... Unable to tell with the JIT compiler, since the method used for testing was simple enough to inline - which resulted in an unrealistic 100x speed difference.
    The above tests do not include the overhead of exception handling, nor for locating the method to be executed - ie, in both the simple method invocation and reflective method invocations, the exact method was known at compile time and so there is no "locative" logic in these timings.
    Major benefit at compile-time:
    Compile-time type safety! If you are looking for a method doSomething, and you typo it to doSoemthing, if you are using direct method invocation this will be identified at compile time. If you are using reflection, it will compile successfully and throw a MethodNotFoundException at run time.
    Similarly, direct method invocation offers compile-time checking of arguments, result types and expected exceptions, which all need to be dealt with at runtime if using reflection.
    Personal and professional recommendation:
    If there is any common theme to the objects you're storing in your hashtable, wrap that into an interface that defines a clear way to access expected functionality. This leaves implementations of the interface (The objects you will store in the hashtable) to map the interface methods to the required functionality implementation, in whatever manner they deem appropriate (Hopefully efficiently :-)
    If this is feasible, you will find it will produce a result that performs better and is more maintainable. If the interface is designed well, it should also be just as extensible as if you used reflection.

Maybe you are looking for

  • Objects in an Array

    I'm having trouble getting my objects into an array. The program compilies just fine, but when you run it, it just outputs all null values. //import necessary classes import java.util.Scanner; import java.io.File; import java.io.IOException; import j

  • Error message: 'Codec not found..'

    Hi all. This is a new error I've never seen before. It's stopping me doing anything at all really. As soon as I start up FCP and click on a sequence I get this message: 'Codec not found. You may be using a compression type without the corresponding h

  • Cannot use DDNS service in china!

    I am use WRT300N V1(Firmware Version: v1.03.6) wireless router in china, and use China Telecom ADSL Broadband service, I want to use DDNS service but never connet to DynDNS.org, please help me to solve the problem,many thanks. Joe

  • ISE ver 1.1.3.124 - DNS Resolution Errors.

    I am having a very strange issue with ISE version 1.1.3.124 running as a VM on UCS. When I login to ISE GUI using my browser I see a large number of Alarms: Alarm Occurred At: Mon Apr 15 19:45:01 UTC 2013 Cause: DNS resolution failure on host device_

  • Firefox Show Bookmark button when Menu is visible

    Just updated to FF25 from FF22, and decided to have the Menu tool bar visible, and all was fine. Until I restarted FF and now my Bookmark Drop down BUTTON is gone. I go to customize, and the button reappears, but as soon as I close the customize wind