I have a class which has an interface as member
Class A {
IProp property;
}
At runtime we assign property with one of the concrete classes implementing IProp.
Say,
A a = new A();
a.property = new IPropImpl();
Now if I have object a, I get the fields using reflection :
Field[] fields = a.getDeclaredFields();
But for field property, the type is returned as IProp. I want to get the concrete type which was assigned to it. ( There maybe multiple concrete types. I want to get the one which is assigned to the field).
Can anyone help me out ?
getDeclaredFields() (or any other method of java.lang.Class for that matter) returns the compile-time data that's available for the class - it cannot return data based on a specific instance you're using.
What you could do is simply retrieve the instance you're holding and query its type:
System.out.println(a.property.getClass());
EDIT:
To address the comments, this can also be done by reflection, but would still have to address a specific instance:
for (Field f : a.getClass().getDeclaredFields()) {
Class<?> cls = f.get(a).getClass();
System.out.println
(f.getName() + " is set with a concrete class of " + cls.getName());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With