简体   繁体   中英

Access a member variable using reflection

I have a Class A, which has a private final member variable which is an object of another class B.

Class A {
  private final classB obj;
}

Class B {
   public void methodSet(String some){
   }

}

I know that class A is a singleton . I need to set a value using the method "methodSet" in class B. I try and access classA and get access to the instance of ClassB in classA .

I do this:

Field MapField = Class.forName("com.classA").getDeclaredField("obj");
MapField.setAccessible(true);
Class<?> instance = mapField.getType(); //get teh instance of Class B.
instance.getMethods()
//loop through all till the name matches with "methodSet"
m.invoke(instance, newValue);

Here I get an exception.

I am not proficient at Reflection. I would appreciate if somebody could suggest a solution or point what's wrong.

I'm not sure what do you mean by ''remote'' reflection, even for reflection you must have an instance of the object in your hands.

Somewhere you need to obtain an instance of A. The same holds for the instance of B.

Here is a working example of what you're trying to achieve:

package reflection;

class  A {
     private final B obj = new B();
}


class B {
    public void methodSet(String some) {
        System.out.println("called with: " + some);
    }
}


public class ReflectionTest {
    public static void main(String[] args) throws Exception{
       // create an instance of A by reflection
       Class<?> aClass = Class.forName("reflection.A");
       A a = (A) aClass.newInstance();

       // obtain the reference to the data field of class A of type B
       Field bField = a.getClass().getDeclaredField("obj");
       bField.setAccessible(true);
       B b = (B) bField.get(a);

       // obtain the method of B (I've omitted the iteration for brevity)
       Method methodSetMethod = b.getClass().getDeclaredMethod("methodSet", String.class);
       // invoke the method by reflection
       methodSetMethod.invoke(b, "Some sample value");

}

}

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM