Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't create instance of an async task by `cls.newInstance()`?

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.

like image 937
Freewind Avatar asked Nov 03 '22 12:11

Freewind


1 Answers

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.

like image 103
Marcin Orlowski Avatar answered Nov 13 '22 02:11

Marcin Orlowski