0

I query a database and get a Bean class, which returns ArrayList<Object>. However I

public static ArrayList<Object> getBeanList(){

    String sql = "....";

    ArrayList<Object> beanList = DBUtil.getBeanList(sql, new ConfDetailsBean());

    return beanList;
}

In the calling function of above helper method, I have to cast ArrayList<Object> to required class before I can work the beanList:

ArrayList<Object> beanObjList = getBeanList();  //helpermethod call

ArrayList<ConfDetailsBean> confDetailsBeanList = new ArrayList<ConfDetailsBean>();

for(Object bean: beanList)
    confDetailsBeanList.add((ConfDetailsBean) bean);

Now, in helper method DBUtil.getBeanList(sql, new ConfDetailsBean());, ConfDetailsBean is hardcoded.

How to make the helper method generic, so that I can pass any Bean Object?

parishodak
  • 4,506
  • 4
  • 34
  • 48

1 Answers1

2

You should introduce a (method-scoped) type-parameter T and explicitly pass a Class<T>, so that you could be able to instantiate T at Runtime.

Also, returning a List instead of ArrayList could give you more flexibility:

public static List<T> getBeanList(Class<T> clazz) {

    String sql = "....";

    List<T> beanList = DBUtil.getBeanList(sql, clazz);

    return beanList;
}

Having this, your code will shorten a bit:

List<ConfDetailsBean> confDetailsBeanList = getBeanList(ConfDetailsBean.class);  
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • thank you. got it working in some what convoluted way `ArrayList beanObjList =(ArrayList) runner.query(conn, sql, new BeanListHandler((Class) beanObj.getClass()));` – parishodak Jan 06 '16 at 10:46
  • i am guessing `(Class) beanObj.getClass())` is equivalent to `ConfDetailsBean.class` – parishodak Jan 06 '16 at 10:48