How do we cast a variable dynamicaly at runtime?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   kenny_ma
Posted On:   Friday, June 15, 2001 01:08 PM

Hello guys,



Does anybody know how to cast a variable into a type only know at runtime? namely,


Having String s = ;

and given a string type = "Integer", "java.sql.Date", or "Float"


In case of "Integer", the result should be an object of Integer;

while "java.sql.date" should result in an object of java.sql.Date
(like calling new java.sql.Date(s);) ... etc



Any hints will be highly appreciated,

Re: How do we cast a variable dynamicaly at runtime?

Posted By:   Michael_Wax  
Posted On:   Friday, June 15, 2001 03:12 PM

Here is something that gets you part of the way there for the numeric types: If the type string is the fully qualified class name (e.g., java.lang.Float), you can do the following:

Class c = Class.forName(type);
Class[] classArray = {String.class};
Constructor constructor = c.getDeclaredConstructor(classArray);
Object params = {yourString};
Object o = constructor.newInstance(params);

Note that you will still need to cast the object you get, possibly using a switch statement. Note also that I have ignored exception handling.


Unfortunately, this code will not work for java.sql.date, which does not have a constructor which takes a String argument.

Re: How do we cast a variable dynamicaly at runtime?

Posted By:   AlessandroA_Garbagnati  
Posted On:   Friday, June 15, 2001 02:57 PM

Hi,

Java allows you to create objects at runtime using reflections. (check this Forum thread).


Once you have a variable declared as String, you cannot cast it back to another class, unless the class is a superclass of the one you want to use.


Again, check out the javadoc of java.lang.Class and the classes related to the reflections package.

About | Sitemap | Contact