[英]Cannot cast to an Extended Class in Java
我环顾四周寻找类似的问题但找不到与之相符的东西。
我正在尝试扩展内置的JSONObject以添加一些功能,如下所示:
public class MyJSONObject extends JSONObject {
// Easily return an integer from a JSONObject, handling when the value is null.
//
public Integer getIntegerUnlessNull(String key) throws JSONException {
String key_value = this.getString (key);
if ( key_value.equals("null") ) {
return null;
} else {
return Integer.parseInt( key_value );
}
}
}
但是,当我尝试转换它时,我得到一个java.lang.ClassCastException
错误:
private JSONArray jsonClients;
MyJSONObject clientJSONRecord;
clientJSONRecord = (MyJSONObject) jsonClients.getJSONObject(0);
完整的错误消息是:
java.lang.ClassCastException: org.json.JSONObject cannot be cast to com.insightemissions.trak.extensions.MyJSONObject
有帮助吗?
干杯,
J.P
jsonClients.getJSONObject(0)
返回JSONObject
类型的对象,它是您的父类型。
您无法将其强制转换为继承的类型。 它只能以另一种方式工作,即将继承的类转换为父类。 这与您的对象无关,它只是继承的工作方式。
因为从方法中获取了JSONObject
的实例,并且无法控制它的实例化方式,所以可以在MyJSONObject
类中添加一个构造函数,以便从父对象创建一个对象:
public MyJSONObject(JSONObject parent) {
super(parent.toString());
}
并以这种方式使用它:
JSONObject parent = jsonClients.getJSONObject(0);
MyJSONObject child = new MyJSONObject(parent);
您遇到的问题是JSONArray
中的对象(我假设JSONArray
对象是由库创建的)不包含您定义的MyJSONObject
对象。
只有在您自己创建JSONArray
并使用MyJSONObject
对象填充它时,您的代码才MyJSONObject
。
鉴于你试图通过这种“扩展功能”实现的目标,我认为继承是一种过度杀伤力。
为什么不使用辅助方法?
public Integer getIntegerUnlessNull(JSONObject, String key) throws JSONException {
String key_value = object.getString (key);
if ( key_value.equals("null") ) {
return null;
} else {
return Integer.parseInt( key_value );
}
}
然后你可以这样做:
Integer getInteger = getIntegerUnlessNull(object, "key");
if (getInteger == null) {
// if null do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.