The android code is simple:
public void createNewTask(View v) {
    try {
        MyTask task = MyTask.class.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
private class MyTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        return null;  
    }
}
But when invoking createNewTask method, it will throw an exception:
Caused by: java.lang.RuntimeException: 
    java.lang.InstantiationException: com.example.MyActivity$MyTask
    at com.example.MyActivity.createNewTask(MyActivity.java:214)
    ... 14 more
    Caused by: java.lang.InstantiationException: com.example.MyActivity$MyTask
    at java.lang.Class.newInstanceImpl(Native Method)
    at java.lang.Class.newInstance(Class.java:1440)
    at com.example.MyActivity.createNewTask(MyActivity.java:211)
But if I choose another class, e.g.
MyActivity task = MyActivity.class.newInstance();
Everything will be fine.
Where is wrong in my code? I tested it in an android phone with android 2.3.6.
Found two ways to solve this problem:
public static class MyTask {
}
or
private static class MyTask {
    public MyTask(){}
}
According to documentation:
InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.
Try adding nullary constructor to your class:
public MyTask() {}
EDIT
According to this documentation:
Class.newInstance() requires that the constructor be visible; Constructor.newInstance() may invoke private constructors under certain circumstances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With