javagenericscollectionsapache-commons-dbutils

How to design method handling a Collection in Java based on the class type passed?


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?


Solution

  • 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);