Reputation: 9261
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 i.e. 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.
Upvotes: 1
Views: 1407
Reputation: 117587
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);
Upvotes: 1
Reputation: 881
You need to implement the "Factory Pattern".
Make a static method:
public class Song extends Model {
...
public static Song createSong() {
return new Song(...);
}
}
Upvotes: 0