1

Given:

public class A {
   public int n;
   public int func(Object arg) {...}
   ...
}

public class B {
    private A myA;
    ...
}

private B myB;

When using reflection on myB I get the field for myA; how can I access the members and methods of class A with it? For example let's say I got a string "myA.n" and given object myB I need to access myA.n

Class<?> c = B.class; // or myB.getClass()
Field f = c.getField("myA");
int p = ???????? // reflection for int p = myA.n;
int q = ???????? // reflection for int q = myA.func(new Integer(3));
ilomambo
  • 8,290
  • 12
  • 57
  • 106
  • 1
    `myA.class` doesn't work. You need `myA.getClass();` – Marko Topolnik Jun 04 '13 at 12:03
  • @MarkoTopolnik I have similar reflection **working code** with myA.class. My code actually is a method `private void myMethod(Class> c)` and I call it with `myMethod(myA.class);`. But `getClass()` will work too – ilomambo Jun 04 '13 at 12:09
  • 1
    Unless you have a class which is *called* `myA`, that is not even valid Java syntax. – Marko Topolnik Jun 04 '13 at 12:18
  • @MarkoTopolnik Sorry, my mistake. You are right, it should read `A.class` I will edit. – ilomambo Jun 04 '13 at 12:23
  • @MarkoTopolnik I corrected the code in the question. `myA` is a field of `myB`, so the `Class>` object should be of type B. – ilomambo Jun 04 '13 at 12:44

1 Answers1

0

You will need to call Class.getField() and iterate through them looking for the correct function.

For (Field field : class.getField()) {
  if (field.getName().equals("...")) {
    ...
  }
}

The reason for this is that there can be multiple fields with the same name and different parameter types (ie the field name is overloaded).

getField() returns the public field in the class, including those from superclasses.

Ahmad Azwar Anas
  • 1,289
  • 13
  • 22
  • Sorry Ahmad, I don't fully understand you. In any case, this is not a complete answer. I would like to see how would code the `???????` in my question, fully. – ilomambo Jun 04 '13 at 12:26