Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get concrete class of interface field using Java reflection

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 ?

like image 988
Aneesh Avatar asked Dec 03 '25 17:12

Aneesh


1 Answers

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());
}
like image 87
Mureinik Avatar answered Dec 05 '25 05:12

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!