Eliminate unchecked cast Warning


In Java, you often convert an Object type into the Map, List, etc. you want. The usual practice is to:
Object obj = ....; Map<String, String> castMap = (HashMap<String, String>) obj;

Unchecked cast warning will be generated here, and those with code cleanliness will find a way to kill it. The solution is to add an annotation @SuppressWarnings("unchecked") to the method. The more elegant solution is to provide a tool class, and then write a special cast method to do this work.

    @SuppressWarnings("unchecked") public static <T> T cast(Object obj) { return (T) obj; }

So the above can be solved like this:

Object obj = ....; Map<String, String> castMap = cast(obj); //import static method

The more robust one needs to deal with the ClassCastException that will be thrown here, and it's OK to make a warn log and do anything.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325762016&siteId=291194637