我在创建匿名对象和调用父类(super class)中实现的函数时遇到问题。
异步任务
public abstract class AsyncTask<Params, Progress, Result>{
protected abstract Result doInBackground(Params... params);
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
//implementation. Shortly, it calls doInBackground(params).
}
}
HttpRequestTask
public abstract class HttpRequestTask<T> extends AsyncTask<String, Void, AsyncTaskResult<ResponseEntity<T>>>{
@Override
protected AsyncTaskResult<ResponseEntity<T>> doInBackground(String... url) {
//implementation
}
//...create other abstract methods (no relation with the question)...
public HttpRequestTask authenticate(SharedPreferences authPreferences) {
this.authPreferences = authPreferences;
return this;
}
}
我使用这样的类:
new HttpRequestTask<Player, Void>(Player.class) {
//...implementation of abstract methods from HttpRequestTask
}
.authenticate(authPreferences)
.execute("any string");
运行这个,我得到这个异常:
java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]
at com.edu.antechamber.controller.HttpRequestTask.doInBackground(HttpRequestTask.java:41)
第 41 行是:public abstract class HttpRequestTask<T> extends AsyncTask<String, Void, AsyncTaskResult<ResponseEntity<T>>>
我应该说 doInBackground()
中的代码未执行,因为在执行第一行之前出现异常。
我认为问题是在我创建匿名对象时出现的 new HttpRequestTask<Player, Void>(Player.class) {...}
, 调用 authenticate(...)
,这将返回此(匿名对象),并调用 execute("any string")
. execute()
应该调用doInBackground("any string")
,但我认为它用一些 Object
调用 doInBackground相反。
Android Studio 给我这个警告:
Unchecked Call to 'execute(Params…)' as a member of raw type 'android.os.AsyncTask'
如果我删除 .authenticate(authPreferences)
部分,应该没有任何区别,因为 authenticate()
返回 this
,但与直觉相反,一切又恢复正常了。
同理,如果我初始化authPreferences
在HttpRequestTask
的构造函数,它再次工作。但我真的需要得到 authenticate()
函数工作,否则我会有很多构造函数。
如果您能帮助我解决这个问题,我将不胜感激。
最佳答案
虽然可以通过传递一个数组来解决
execute(new String[]{"/api/player/55707e1eb7396de50dcef73d"})
而不是一个字符串参数
execute("/api/player/55707e1eb7396de50dcef73d")
问题出在这一行,而不是
public HttpRequestTask authenticate(SharedPreferences authPreferences)
如@user所说,应该是
public HttpRequestTask<T> authenticate(SharedPreferences authPreferences)
非常感谢!
关于java - 在匿名对象上调用父类(super class)方法 AsyncTask.execute() new HttpRequestTask<...> extends AsyncTask<...>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236158/