我想根据Java和Kotlin提出简单的Volley POST请求。我在应用程序中同时使用两种语言,因此我尽力使用两种语言。
我在Kotlin的以下VolleyClass中浏览了this教程:
WolfRequest(val url class:String,
val结果:(JSONObject)-> Unit,
val错误:(字符串)->单位){
fun POST(vararg params: Pair<String, Any>) {
// HashMap to pass arguments to Volley
val hashMap = HashMap<String, String>()
params.forEach {
// Convert all Any type to String and add to HashMap
hashMap[it.first] = it.second.toString()
}
// Make the Http Request
makeRequest(Request.Method.POST, hashMap)
}
private fun makeRequest(method: Int, params: HashMap<String, String>) {
// Creating a StringRequest
val req = object : StringRequest(method, url, { res ->
// Creating JSON object from the response string
// and passing it to result: (JSONObject) -> Unit function
result(JSONObject(res.toString().trim()))
}, { volleyError ->
// Getting error message and passing it
// to val error: (String) -> Unit function
error(volleyError.message!!)
}) {
// Overriding getParams() to pass our parameters
override fun getParams(): MutableMap<String, String> {
return params
}
}
// Adding request to the queue
volley.add(req)
}
// For using Volley RequestQueue as a singleton
// call WolfRequest.init(applicationContext) in
// app's Application class
companion object {
var context: Context? = null
val volley: RequestQueue by lazy {
Volley.newRequestQueue(context
?: throw NullPointerException(" Initialize WolfRequest in application class"))
}
fun init(context: Context) {
this.context = context
}
}
}
我正在尝试从Java.Class访问此代码以进行POST请求:
WolfRequest.Companion.init(getApplicationContext());
HashMap <String, String> params = new HashMap <> ();
params.put("id", "123");
new WolfRequest(config.PING_EVENTS,*new WolfRequest()*
{
public void response(JSONObject response) {
Log.e("Ping","PING");
}
public void error(String error) {
Log.e("Ping",error);
}
}).POST(params);
它给我一个错误(新WolfRequest()),它说:无法从最终的“ ... wolfrequest.kt”继承
我确实没有收到错误,这是什么问题?
谢谢
最佳答案
默认情况下,kotlin中的类是最终的。要创建无最终类,您需要将其声明为open
。所以open class WolfRequest
在Java中使用new WolfRequest() {}
可以创建扩展WolfRequest
的匿名类,因此您将从继承的类继承该错误。
要实际调用WolfRequest的构造函数,您需要传递三个参数。就像是:
new WolfRequest("", (s) -> Unit.INSTANCE, (s) -> Unit.INSTANCE){
....
}