0

Here I get the methods from a Tree Class.

Class c = o.getClass();
Method m[] = c.getDeclaredMethods();

The methods are:

public Tree<T>[] getChildren(){
    return children;
}

public T getValue(){
    return value;
}

In my print function I want to invoke getChildren() until I get to the bottom of the tree.

There is no problem in getting the return value from getValue() or the FIRST getChildren()

System.out.println(m[0].invoke(o));
System.out.println(m[1].invoke(o));

The m[1].invoke returns a Tree. I want to access the getValue from that Tree now. But it has no methods.

Object tempObj = m[1].invoke(o);
Class tempClass = tempObj.getClass();
Method[] m2 = tempClass.getDeclaredMethods();

m2 is an array that should contain the same methods as the original Tree, but its empty.

  • 1
    Why not just call the methods the way you're meant to, i.e. without using reflection? If in any case you insist on using reflection, note that `Method#invoke(...)` will return `Object` so it's up to _you_ to know what the return value actually is and cast accordingly. – Thomas May 02 '17 at 12:34
  • In `Class tempClass = tempObj.getClass();`, did you check the actual value of `tempClass`? – Thomas May 02 '17 at 12:36
  • tempObj is the Tree and I can see it contains both my subtrees, how do I access those subtrees? – Simon Andersson May 02 '17 at 12:42
  • 1
    Never use reflection, unless you absolutely have to. [It's somewhat dangerous](http://stackoverflow.com/questions/3002904/what-is-the-security-risk-of-object-reflection). – MC Emperor May 02 '17 at 13:04
  • If `tempClass` is `Tree.class` (that's what my comment was about) then `tempClass.getDeclaredMethods()` should return the methods declared in `Tree`. If it doesn't then the error is somewhere else and you should post a [mcve]. – Thomas May 02 '17 at 14:12
  • I solved it! The invoke method returned a Tree of Arrays instead of Tree, so I just took each element and casted them to class. – Simon Andersson May 02 '17 at 20:44

0 Answers0