如何通过反射调用类的字段成员的方法?

时间:2014-04-10 10:37:27

标签: java android reflection

下面的方法给了我一个 NoSuchMethodException

package a.b.c;
class A{
    B b;
}


package x.y.z;

class Main{

    private void doSomething(){
        try{
            Class<?> aClass = Class.forName("a.b.c.A");
            Field bField = aClass.getDeclaredField("b");
            bField.setAccessible(true);

            //This didn't work as it gives me a NoSuchMethodException
            Class<?> bObj = bField.getType();
            Method cFilterMethod = bObj.getMethod("setColorFilter", new Class[]{Integer.class, PorterDuff.Mode.class});
            cFilterMethod.invoke(bObj, new PorterDuffColorFilter(0xffff00,PorterDuff.Mode.MULTIPLY));   

            // So I tried looking for all the methods inside bObj
            // This prints all the methods of the java.lang.Class instead of class B
              Method[] methods = bObj.getMethods();
              for(Method method : methods){
                    Log.d("TAG", ""+ method.getName());
              }

        }// Exception Handling Code
    }
}

所以,基本问题是,

  

如何调用类的字段成员的方法?

我必须调用字段 b setColorFilter 方法,该字段是 A 类的默认成员。

我使用反射的原因是上面的包a.b.c 是封闭源。

PS:我已经检查了this,我无法在那里找到问题的解决方案吗?

0 个答案:

没有答案