我有一个 VisitMapper.java
类,它是从 JSONObject
类扩展而来的。在 VisitMapper.java
类中,我覆盖了 JSONObject
类 getString()
和 getJSONObject()
的两个方法。这是我的代码:
VisitMapper.java
public final class VisitMapper extends JSONObject{
private static final String DISPLAY_KEY = "display";
private VisitMapper() {
}
public static Visit map(JSONObject jsonObject) throws JSONException {
Visit visit = new Visit();
visit.setUuid(jsonObject.getString("uuid"));
visit.setVisitPlace(jsonObject.getJSONObject("location").getString(DISPLAY_KEY));
visit.setVisitType(jsonObject.getJSONObject("visitType").getString(DISPLAY_KEY));
visit.setStartDate(DateUtils.convertTime(jsonObject.getString("startDatetime")));
visit.setStopDate(DateUtils.convertTime(jsonObject.getString("stopDatetime")));
return visit;
}
@Override
public String getString(String name) throws JSONException {
String tempName = "";
System.out.println("getString() is being called: "+name);
if (this.has(name) && !this.isNull(name)){
tempName = super.getString(name);
}
return tempName;
}
@Override
public JSONObject getJSONObject(String name) throws JSONException {
JSONObject tempObject = null;
System.out.println("getJSONOBJECT() is being called");
if (this.has(name) && !this.isNull(name)){
tempObject = super.getJSONObject(name);
}
if (tempObject==null){
}
return tempObject;
}
}
我检查了我的 logcat,未打印 System.out.println()
调用。我经历了一些此类问题,他们提到这些方法不应该是包的静态或本地方法,它们不应该是私有(private)的。您必须继承父类等。使用这两种方法不存在此类问题。我从 JSONObject.java
继承我的 java 类。我无法理解我错在哪里。感谢您的帮助。
最佳答案
如果 JsonObject 的实例是 VisitMapper (JsonObject json = new VisitMapper()
),map(JsonObject jsonObject)
中的 Json 对象将仅使用您覆盖的方法。
如果 JsonObject 的实例是它自己 (JsonObject json = new JsonObject()
),getString
和 getJsonObject
方法将来自 JsonObject .类
要检查一个对象的实例,你可以这样写:
if(jsonObject instanceof VisitMapper){
//here you can access your override methods
} else if (jsonObject instanceof JsonObject) {
//here you cannot access your override methods
}
更新
添加 Jon Skeet 提供的关于多态性的链接:https://docs.oracle.com/javase/tutorial/java/IandI/override.html
关于java - 覆盖未在 Android 中调用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812980/