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:
- [Solved] Java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
- [Solved] Exception in thread “main” java.util.ConcurrentModificationException
- Java – Convert bytes to unsigned bytes
- [Two Solutions] non-static method xxx() cannot be referenced from a static context
- [Solved] Java Call Error: java.lang.IllegalArgumentException: wrong number of arguments
- Roman to Integer LeetCode Java
- [leetcode] 140. Word break II word split II
- [Problems with the use of internal classes] No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclo
- Java error: No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing