【问题标题】:Return new instance of extending class from superclass从超类返回扩展类的新实例
【发布时间】:2013-02-14 09:11:04
【问题描述】:

我正在构建一个具有多个扩展“模型”类的类的 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”方法,该方法将返回的不是 Model 类的实例,而是 Artist、Album 等类的实例。

【问题讨论】:

  • 你想达到什么目的?

标签: java android


【解决方案1】:

给你:

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

然后像这样使用它:

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

【讨论】:

  • 如果不将类作为参数传递就没有办法做到这一点?
【解决方案2】:

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

制作一个静态方法:

public class Song extends Model {

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

【讨论】:

  • 我已经进一步解释了我的问题。
猜你喜欢
  • 1970-01-01
  • 2012-01-18
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
  • 2015-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多