gpt4 book ai didi

android - 无法通过 `cls.newInstance()` 创建异步任务的实例?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:31 25 4
gpt4 key购买 nike

android代码很简单:

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;
}
}

但是在调用createNewTask方法时,会抛出异常:

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)

但是如果我选择另一个类,例如

MyActivity task = MyActivity.class.newInstance();

一切都会好起来的。

我的代码哪里错了?我在装有 android 2.3.6 的 android 手机上对其进行了测试。

最佳答案

找到了解决这个问题的两种方法:

public static class MyTask {
}

private static class MyTask {
public MyTask(){}
}

根据 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.

尝试向您的类中添加 nullary 构造函数:

public MyTask() {}

编辑

根据 this documentation :

Class.newInstance() requires that the constructor be visible; Constructor.newInstance() may invoke private constructors under certain circumstances.

关于android - 无法通过 `cls.newInstance()` 创建异步任务的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13157795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com