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?
Object derivedClass = baseClass.getChild().getClass();
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?)
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: derivedClass.cast(differentClassObject)
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.