0

There are several related questions on StackOverflow, but none seem to solve my problem.

Consider the following code:

public class MainActivity extends Activity {
    // ...


    private class MyClass {

        protected void myMethod() {
                // ...
                MyExtendedClass var = (MyExtendedClass)Class.forName("com.example.myapp.MainActivity$MyExtendedClass").newInstance();
                // ...
        }
    }

    private class MyExtendedClass extends MyClass {
        // ...
    }   
}

When the line initializing var is called, I get the following error:

java.lang.InstantiationException: can't instantiate class com.example.myapp.MainActivity$MyExtendedClass; no empty constructor

I cannot figure out why this is happening.

Even if I add the following constructors to their corresponding classes, I still get the same error:

public MyClass() {
    // nothing
}

public MyExtendedClass() {
    super();
}
Walter
  • 11
  • 2

1 Answers1

0

Look at this postinstance inner class
and here is some modify to work with your case:

Class<?> innerClass = Class.forName(MainActivity.class.getName() + "$MyExtendedClass");
                    Constructor<?> ctor = innerClass.getDeclaredConstructor(MainActivity.class);
                    ctor.setAccessible(true);
                    MyExtendedClass var = (MyExtendedClass)ctor.newInstance(MainActivity.this);
Community
  • 1
  • 1
justHooman
  • 3,044
  • 2
  • 17
  • 15