简体   繁体   中英

Return new instance of extending class from superclass

I'm building an Android application that has multiple classes extending a 'Model' class.

This is my code right now:

public class Model {

    protected int mId;

    public int getId() { return mId; } 

    public Model(JSONObject json) {
        try {
            mId = json.getInt("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public Class<? extends Model> getBy(String property, String value) {
        // should return new instance of extending class
        return null;
    }

}

public class Song extends Model {

    protected String mName;
    protected String mArtist;
    protected int mDuration;

public String getName() { return mName; }
public String getArtist() { return mArtist; }
public int getDuration() { return mDuration; }

    public Song(JSONObject json) {
        super(json);

        try {
            mName = json.getString("name");
            mArtist = json.getString("artist");
            mDuration = json.getInt("duration");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}

I'm trying to create a method in the Model class to return a new instance of the class extending it.

The idea is that multiple classes could extend the Model class ie Artist, Album. These classes should have a 'getBy' method that would return instances of not the Model class but instances of the Artist, Album, etc class.

Here you go:

public <T extends Model> T getBy(Class<T> clazz, JSONObject json) throws Exception
{
    return clazz.getDeclaredConstructor(json.getClass()).newInstance(json);
}

Then use it like:

Model model = ...;
Song song = model.getBy(Song.class, someJson);

You need to implement the "Factory Pattern".

Make a static method:

public class Song extends Model {

...
    public static Song createSong() {
       return new Song(...);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM