Showing posts with label dynamic. Show all posts
Showing posts with label dynamic. Show all posts

Tuesday, April 24, 2012

Return List of Dynamic object types from Method

Sometimes we want to convert the list of objects into a desired data type list. Here is one simple example which returns a list of objects into list of Strings, assuming that all the objects will be of type String.


// method with generic return type
public <T> List<T> getMyList(Class<T> elementType, List objList)
{
    List<T> list = new ArrayList<T>();
    
    for(Object obj : objList)
    list.add(elementType.cast(obj));
    
    return list;
}

// calling the method
getMyList(String.class, objList);