Originally posted by Firas Majdi: how i could choose the casting i want on dynamically,
offcourse this will result a Class Cast Exception
I'm not sure I understand the question.
Casting of base types is another story, but casting of reference types is pretty much done only for compile-time type safety. (I guess it can also be used to test for null or cause an exception to be thrown, but there are simpler ways to do those things.)
Casting from one reference type to another doesn't do any conversion or anything, it just obtains a reference that is of a different type. So how would it be useful to cast dynamically?
tell me what to do?
Well if you are trying to convert from the String "4" to a java.lang.Short, then use the static Short.valueOf() method (or the Short constructor that accepts a String).
If you are trying to understand how and why the Class.cast() method works, keep in mind that it's pretty much pointless outside the context of generics. And it does nothing useful at runtime [though it does throw an exception if a call to Class.isInstance() fails] as it simply returns its argument.
well to be more accurate i dont want to convert from string to short the case that i want to convert from string to any type i choose on run time but without using if statements , i get the type from an xml file and use it in my project depending on certain rules
That's not really casting, but converting. And there really isn't a single java command that does this, so you will need to have some form of if or switch statement, or use something like the Strategy design pattern.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Sep 20, 2005
Originally posted by Firas Majdi: well to be more accurate i dont want to convert from string to short the case that i want to convert from string to any type i choose on run time but without using if statements , i get the type from an xml file and use it in my project depending on certain rules
In general there's no way to do this. Some classes just can't be converted from Strings.
However, they way some classes (such as DefaultFormatter) handle this is to presume that the class in question has a constructor that takes a single String argument, and invoke that constructor via reflection. Could this approach would work for you? [ March 03, 2008: Message edited by: Brian Cole ]