I have an android app with a Business Object (let’s call it SuperClass) that has several derived classes (let’s call them DerviedClassA, DerivedClassB etc). Each object has a constructor which takes a Cursor object with multiple rows and assigns appropriate properties based on the current row in the cursor
public Class DerivedClassA
{
// properties
private int X;
// etc
public DerivedClassA(Cursor data)
{
X = data.getInt(data.getColumIndex(ColumnX));
// etc
}
}
I then have BO methods which return an ArrayList of the derived class, like below:
public static ArrayList<DerivedClassA> getDerivedClassAList(Cursor data)
{
ArrayList<DerivedClassA> list = new ArrayList<DerivedClassA>();
for(int i=0;i<data.getCount();i++)
{
data.moveToPosition(i);
DerivedClassA wev = new DerivedClassA(data);
list.add(wev);
}
data.close();
return list;
}
And so on for DerivedClassB, DerivedClassC etc. To avoid this duplication, I want to be able to have a single method which somehow takes in the type of the derived class, invokes the appropriate constructor of that derived class, and returns an ArrayList of the appropriate derived class. Something like:
public static ArrayList<T extends SuperClass> getDerivedClassList(Cursor data)
{
ArrayList<T> list = new ArrayList<T>();
for(int i=0;i<data.getCount();i++)
{
data.moveToPosition(i);
T wev = new T(data);
list.add(wev);
}
data.close();
return list;
}
However, I’m not sure if it’s actually possible, or how to go about it. Any pointers would be appreciated.
Yes, it is.
Refer:
http://download.oracle.com/javase/tutorial/extra/generics/methods.html
http://download.oracle.com/javase/tutorial/java/generics/genmethods.html