覆盖未在 Android 中调用的方法

Override methods not being called in Android

我有一个从 JSONObject class 延伸而来的 class VisitMapper.java。在 VisitMapper.java class 中,我覆盖了 JSONObject class 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() 呼叫未打印。我经历了一些此类问题,他们提到这些方法不应该是包的静态或本地方法,它们不应该是私有的。你必须继承父class等。用这两种方法就不会有这种问题。我从 JSONObject.java 继承了我的 java class。我无法理解我错在哪里。感谢您的帮助。

如果 JsonObject 的实例是 VisitMapper (JsonObject json = new VisitMapper()),map(JsonObject jsonObject) 中的 Json 对象将仅使用您重写的方法。

如果 JsonObject 的实例本身是 (JsonObject json = new JsonObject()),方法 getStringgetJsonObject 将来自 JsonObject.class

要检查一个对象的实例,你可以这样写:

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 提供的关于多态性的link:https://docs.oracle.com/javase/tutorial/java/IandI/override.html