Yes, you can do it, but if you are really using anything from the Collections framework, which includes ArrayList, then you want to avoid casts like the plague. An incorrect cast will cause your entire application to crash.
Originally posted by bhaswar goswami: I have a situation where i need to cast java objects dynamically .
With all due respect, I seriously doubt that you are.
ArryList list =( type )paramObject ; // This type i wil know dynamically while calling the Method.
You could simply cast to ArrayList. Why would you want to cast to something else?
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
I have a situation where i need to cast java objects dynamically .
I agree with Ilja that this is something that you do not want or need to do.
- You write the source code before you compile or run the program. - You say that you don't know what you want to cast the variable to before runtime.
Those two are in conflict with eachother. At the moment you write the source code, you already know to what type of variable you are assigning the result of the cast expression to - you already know it at compile time, not at runtime.
So you must be confusing some things.
Can you explain why you think you need to do this? [ July 18, 2006: Message edited by: Jesper Young ]
Care should be taken not to use "instanceOf" operator in large loops etc since it can adversely affect performance.
Whoa! where did that come from? The instanceOf operator is used (invisibly) every time a reference cast is done so it is very frequent in Java programs and has to be fast. String thing = (String) object ; // there is an instanceOf check being done - otherwise how would you get a class cast exception?? Bill