Dmitry
Dmitry

Reputation: 3038

Java Reflection: Get a Field's Value where the Field is of an Interface Type

Say, there is a class (A) which has a field (myField). The type of the field myField is an interface (I). Everything is public.

I need to invoke a method of the class which is a type of the *myField *. My code is the following:

 Field myField = getField(myClass, "fieldName");
 Class fieldClass = myField.getType(); // returns I

 try {
        Class[] params = {String.class};
        Method method = fieldClass.getMethod("methodName", params);

        Object[] paramsObj = {new String("input")};
        boolean result = (Boolean) method.invoke(WHAT_MUST_I_PUT_HERE, paramsObj);
} catch...

As you can see the problem is I can't do thing like:

WHAT_MUST_I_PUT_HERE = myField.getClass() // returns Field

Can somebody help me?

EDIT: I have tried to use

TargetClass o = (TargetClass) myField.get(myClass)

but caught the IllegalArgumentException

Upvotes: 3

Views: 10694

Answers (2)

Dmitry
Dmitry

Reputation: 3038

The solution is:

    Class myClass = service.getClass();
    Field myField = getField(myClass, "fieldName");

    TargetClass target = null;
    try {
        target = (TargetClass) myField.get(service);
    } catch (IllegalAccessException e) {
        e.printStatckTrace();
    }

    Class fieldClass = myField.getType();
    try {
        Class[] params = {String.class};
        Method myMethod = fieldClass.getMethod("methodName", params);

        String paramItem = new String("value");
        Object[] paramsObj = {paramItem};
        boolean result = (Boolean) myMethod.invoke(target, paramsObj);         
    } catch ...

Upvotes: 0

Andrzej Doyle
Andrzej Doyle

Reputation: 103837

The first argument to the invoke method is simply the object on which to call the method. So let's say you got a non-static method corresponding to I.m(String). You need an instance of I to invoke it on (since this is a non-static method).

Presumably you want to call the equivalent of myField.m(input) via reflection, hence you simply pass in myField as the first argument:

boolean result = (Boolean) method.invoke(myField, paramsObj);

Upvotes: 7

Related Questions