Search code examples
javareflectionprivate

Reflection - Casting an Object to it's unknown Superclass on the fly?


Hi I am in a situation where I have access to a class House Which extends Foundation(Please note the Class names are Hypothetical). And I have an object of type House, I would like to get the field Foundation.width which is set to private. I have come up with the code:

1.) Field list = houseObject.getClass().getSuperclass()
                                     .getDeclaredField("width");
2.) list.setAccessible(true);
3.) this.width = (double)list.get(foundationObject);

The problem is with line #3 I do not have access to a foundationObject, I have access to a houseObject, and since I do not truly know the Class of Foundation at compile time I cannot cast (Foundation)foundationObject.

Is there a solution to this? Thank you for your help.


A better way to word this question may also be: Can I get a non-static object of type Superclass from an object?


Solution

  • Try list.get(houseObject) The accessibility change will cascade to sub classes and hence the field will be accessible directly from houseObject.