Convert Object to List, avoiding Unchecked cast: ‘java.lang.Object’ to ‘java.util.List

If you need to convert an object into a list in Java, most people will directly use coercion type conversion: (list < String>) Obj so. In this way, cast compilation will prompt unchecked cast: 'Java. Lang. object' to 'Java. Util. List & lt; java.lang.String>', the compiler means that the cast does not do type checking, the cast is not safe, it may throw an exception and cause the program to crash. In many blogs, some people suggest using @ suppresswarnings ("unchecked") to solve compiler warnings. This method is extremely inappropriate, because it is only used to tell the compiler to ignore warnings, but warnings actually exist

The right way to do it:

public static Object getObj() {
    List<String> list = new ArrayList<>();
    list.add("1");
    list.add("ab");
    return list;
}
public static void main(String[] args) {
    Object obj = getObj();
    List<String> result = new ArrayList<>();
    if (obj instanceof ArrayList<?>) {
        for (Object o : (List<?>) obj) {
            result.add(String.class.cast(o));
        }
    }
    result.forEach(System.out::println); // output: 1 ab
}

If you want to use a more convenient method, you can call the following function directly

public static <T> List<T> castList(Object obj, Class<T> clazz)
{
    List<T> result = new ArrayList<T>();
    if(obj instanceof List<?>)
    {
        for (Object o : (List<?>) obj)
        {
            result.add(clazz.cast(o));
        }
        return result;
    }
    return null;
}

It takes two parameters, one is obj, which is the list object we need to convert, and then pass in the class of the elements in the list

public static void main(String[] args) {
    Object obj = getObj();
    List<String> list = castList(obj, String.class);
    list.forEach(System.out::println);
}

Similar Posts: