简体   繁体   中英

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?

尝试list.get(houseObject)可访问性更改将级联到子类,因此可以直接从houseObject访问该字段。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM