如何为超类中的List元素使用其他子类

时间:2019-02-05 02:08:31

标签: java android generics

我正在为以下四个类寻找实现泛型(或具有数据结构的更好解决方案)的正确方法。我希望能够在基类GetActivationResponse中使用该方法。想法是将纯Java源代码与依赖于Android平台的源代码分开。

GetActivationResponse:

public class GetActivationResponse extends ResponseMessage {
    protected List<Activation> mActivations;

    public GetActivationResponse(JSONObject jsonObject) throws JSONException {
        super(jsonObject);

        mActivations = new ArrayList<>();

        fromJson(jsonObject);
    }

    @Override
    public void fromJson(JSONObject jsonObject) throws JSONException {
        //get the response DATA.
        if(jsonObject.has("DATA")) {
            JSONArray dataArray = jsonObject.getJSONArray("DATA");
            for(int i = 0; i < dataArray.length(); i++) {
                mActivations.add(new Activation(dataArray.getJSONObject(i)));
            }
        }
    }
}

GetActivationResponseAndroid:

public class GetActivationResponseAndroid extends GetActivationResponse implements Cacheable {
    public GetActivationResponseAndroid(JSONObject jsonObject) throws JSONException {
        super(jsonObject);
    }

    @Override
    public List<ContentValues> getContentValuesList() {
        List<ContentValues> values = new ArrayList<ContentValues>();
        for(int i = 0; i < mActivations.size(); i++) {
            values.add(((ActivationAndroid)(mActivations.get(i))).toContentValues());
        }
        return values;
    }
}

不过,我在这里得到了ClassCastException:

((ActivationAndroid)(mActivations.get(i))).toContentValues()

ActivationAndroidActivation的子类。我的目标是能够使用Activation的任何子类以及Activation本身。我认为这可能涉及仿制药。我尝试将List<Activation> mActivations更改为List<? extends Activation> mActivations,但是编译器告诉我GetActivationResponse中填充列表的行在此行上有错误:

mActivations.add(new Activation(dataArray.getJSONObject(i)));

显然<? extends Activation>意味着您只能使用子类,而不能使用基类本身。 我想在基类中使用fromJSON方法,以了解其与Activation或其任何子类的工作方式相同。

ActivationAndroidActivation的子类,它提供了一种方便的方法将对象转换为List<ContentValues>以用于Android数据库事务:

激活:

public class Activation {
    protected String mApp;
    protected boolean mActivated;

    public Activation(String app, boolean activated) {
        mApp = app;
        mActivated = activated;
    }

    public Activation(JSONObject json) throws JSONException {
        mApp = json.getString("APP");
        mActivated = json.getBoolean("ACTIVATED");
    }
}

ActivationAndroid:

public class ActivationAndroid extends Activation implements AndroidSerial {
    public ActivationAndroid (String app, boolean activated) {
        super(app, activated);
    }

    public ActivationAndroid (JSONObject jsonScale) throws JSONException {
        super(jsonScale);
    }

    public ContentValues toContentValues() {
        ContentValues cv = new ContentValues();
        cv.put(DbSchema.ActivationSchema.COLUMN_ACTIVATED, mActivated);
        cv.put(DbSchema.ActivationSchema.COLUMN_APP, mApp);
        return cv;
    }
}

0 个答案:

没有答案