开发者

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};
 开发者_如何学JAVA       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


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);


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 ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜