Alan Pauley Alan Pauley - 1 year ago 80
Java Question

Java: Can you downcast with a variable?

If I have a few derived classes that have methods that are different than the base class, but similar to each other, can I use a variable to downcast?

for example:

Object derivedClass = baseClass.getChild().getClass();

Perhaps that's too vague and/or not efficient since I could just create empty methods in the base class to bypass this issue (or other tricks I haven't learned), but I'm still curious if it's possible to pass variables into casting or not.

Thanks for your insight!

Edit: to further clarify any confusion, I'm trying to determine if I can do casting using a variable. So say I wanted to cast something as a String (just for argument's sake):

String myObjStr = MyObject.class.getSimpleName();
// Then I want to know if I can cast objects using that variable in the casting
//(so far it doesn't appear to be working but I know that's because its a string.
//Is there some way I can manipulate it so that I CAN cast with it?)

Answer Source

While you can sort of use a Class object to specify what type to cast an object to, it doesn't really help you:

Class<? extends ParentClass> derivedClass = baseClassObject.getChild().getClass();

// The following kind of does the cast you want, but not in a useful way:

The problem is that you still need to statically know the type of the result. The static type of the cast output is only as specific as the static type of the Class object, not the runtime type of the Class object. Thus, even if you have a derivedClass object representing ChildClassOne, you only know that it's a Class<? extends ParentClass>. While the object's cast method will throw an exception for instances of ChildClassTwo, you can't call ChildClassOne methods on the return value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download