2 回答
TA贡献1777条经验 获得超10个赞
最后,对于任何可能喜欢使用这种方式的人,我将函数重写如下:
public fun <T> push(context: Context, url: String, myObject: T,myObjectType : Array<Field>, completion: (response: String) -> Unit) {
val myObjectAsDict = HashMap<String, String>()
val allFields = myObjectType //:Array<Field> = myObjectType!!::class.java.declaredFields
for ( field in allFields) {
if (!field.isAccessible) {
field.isAccessible = true
}
val value = field.get(myObject)
if (value != null)
{
if( field.name != "serialVersionUID") {
myObjectAsDict[field.name] = value.toString()
}
}
}
println(myObjectAsDict)
val queue = Volley.newRequestQueue(context)
val sr = object : StringRequest(
Method.POST, url,
Response.Listener { response ->
println(response)
completion(response)
},
Response.ErrorListener { volleyError ->
Common.showVolleyError(volleyError, context)
}) {
override fun getParams(): Map<String, String> {
val params = myObjectAsDict
return params
}
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val params = HashMap<String, String>()
params["Content-Type"] = "application/x-www-form-urlencoded"
params["X-Requested-With"] = "XMLHttpRequest"
return params
}
}
sr.retryPolicy = DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
queue.add(sr)
}
并使用它如下:
var myClass = MyClass()
VolleyFunctions.push(this,"URL",myClass, MyClass::class.java.declaredFields)
{
response->
myClass = Gson().fromJson(response, MyClass::class.java)
println("myClass.Name${myClass.name}")
}
TA贡献1853条经验 获得超9个赞
使基类包含一个抽象方法返回Map<String, String>命名为 example getConvertedParams。此方法应将自身转换为Map<String, String>:
val params = HashMap<String, String>()
params["attribute1"] = attribute1
params["attribute2"] = attribute2
...
return params
每个请求对象都应该扩展该基类并覆盖该方法。在getParams您发送请求的地方,调用getConvertedParams您的通用请求对象。
override fun getParams(): Map<String, String> {
val params = myObject.getConvertedParams()
return params
}
也不要忘记更改方法签名
public fun <BaseClassName> push(context: Context, url: String, myObject: BaseClassName, completion: (response: String) -> Unit)
添加回答
举报