title: How can I instantiate a member class through reflection on Android
body: <p>I have a saving/loading framework that is supposed to save arbitrary object graphs.  This includes instances of non-static nested classes.</p>
  
  <p>Nested classes require are owned by the instance of their parent class that created them, and the nested class knows what instance it belongs to using a synthetic field.</p>
  
  <p>As a simple example, I present this class:</p>
  
  <pre><code>public class Foo implements Savable {
    private class Bar implements Savable {
      public void saveState(Saver saver) {
        saver.putInt(3);
      }
    }
    private Bar myBar = new Bar();
    public void saveState(Saver saver) {
      saver.putSavable(myBar);
    }
  }
  </code></pre>
  
  <p>On the "standard" compiler, the following code works just fine to take in an object (<code>myBar</code>), find its parent (a particular instance of <code>Foo</code>), and keep a reference of it with the child:</p>
  
  <pre><code>if (objectClass.isMemberClass()) {
    //We are a member class, which means we are a non-static inner class, and therefore must save our parent.
    Field[] fields = objectClass.getDeclaredFields();
    //We loop through each of our fields to find the synthetic field created by the compiler that points to our parent.
    for (Field f : fields) {
      String name = f.getName();
      //The synthetic field pointing to the parent is named something like "this$0".  At least, with the "standard" compiler it is.
      if (name.startsWith("this$")) {
        f.setAccessible(true);
        Savable parent = (Savable)f.get(objectClass);
        saver.putSavable("_parent", parent);
        break;
      }
    }
    if (!saver.containsKey("_parent")) {
      throw new RuntimeException("Could not find the owner of inner class: " + objectClass);
    }
  }
  </code></pre>
  
  <p>So, like I said, this works just fine in on the "standard" compiler.  Then at load time, something similar happens, except I look for a constructor that takes in an instance of the parent class and instantiate it, passing in the parent.</p>
  
  <p>But!</p>
  
  <p>It doesn't work on the Android VM.  There are no synthetic fields, and the constructors all look normal, like they don't take in a parent instance.</p>
  
  <p>Am I SOL here?  This VM obviously does not like my approach.  Is there anything I can do here without requiring inner classes to know that they need to save a reference to their parent class instance?</p>