1

我正在构建一个具有多个扩展“模型”类的类的 Android 应用程序。

这是我现在的代码:

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();
        }
    }

}

我正在尝试在 Model 类中创建一个方法来返回扩展它的类的新实例。

这个想法是多个类可以扩展模型类,即艺术家、专辑。这些类应该有一个“getBy”方法,该方法将返回不是模型类的实例,而是艺术家、专辑等类的实例。

4

2 回答 2

1

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);
于 2013-02-14T01:03:18.953 回答
0

您需要实现“工厂模式”。

制作一个静态方法:

public class Song extends Model {

...
    public static Song createSong() {
       return new Song(...);
}
}
于 2013-02-14T00:42:00.507 回答