Downcasting using information gained from getClass()
Hi guys,
i'm trying to downcast an Object type back to its original type but i cant seem to get it to work. I am accepting an undefined number of variables as a method parameter. I am receiving it as an Object array(using the basic method(Object args[]) method descriptor). When i come to use the variables i need an efficient way to downcast them back to the type they were when sent to the method.
Is there a way to downcast using information gained from getClass(), or am i going about this the wrong way?
Thanks!
Barry
# 2
Im willing to admit to my simply being totally ignorant, but i dont know the normal way in this situation. I dont know if i made it clear, but the objects i am receiving are not all of the same type. I thought that i would only be able to store them in an array type which was a superclass of every type, Object. I would simply use the (Type)variable but i dont know the type until runtime.
Thanks!
# 4
> Im willing to admit to my simply being totally
> ignorant, but i dont know the normal way in this
> situation. I dont know if i made it clear, but the
> objects i am receiving are not all of the same type.
> I thought that i would only be able to store them in
> an array type which was a superclass of every type,
> Object. I would simply use the (Type)variable but i
> dont know the type until runtime.
>
> Thanks!
If you don't know the type until runtime, what are you planning to do with the object after you've cast it? You can't be simply passing it to a method, because you'd know the type, or at least, enough about it's type to decide which method to invoke, and thus you could simply cast it. So you must be doing something reflective, like inject it into a method, or invoke methods on it reflectively. Either way, the object is of the correct type, regardless of what kind of reference you're pointing at it, so just carry out your reflection and let the JVM worry about whether they're the correct type or not. Casting does not make the object itself change types, it merely allows it to be dereferenced as a different type. There's no need to cast anything in order to reflect upon it
Of course, I may be completely wide of the mark here in guessing what you're trying to do
# 5
That helps:) I dont actually need to use the object, just compare them for type and content. I made a stupid assumption about an earlier point in the program (i dont have working code yet, im just trying to solve the bits that arent straightforward to see if its possible the way im thinking) but this helps me to go back and fix that. Thanks for your help, both of you!