Java - Unchecked Cast Warning background, causes, and solutions

background

When using Spring Boot, access to a payload objects in the controller, then we want to get list from the payload object.

// Controller
public ResponseEntity<Object> method(@RequestBody JSONObject payload) {
	List<?> list = payload.get("list");
}

At this point, we want to list the objects in operation. Suppose we determine the object list is loaded in the Bookmark, we want to call each Bookmark object getContent () method, then we need to first convert the type to Bookmark (type cast) can.

List<?> list = payload.get("list");
List<Bookmark> bookmarks = (List<Bookmark>) list; // will get warning
for (Bookmark bookmark : list) {
	bookmark.getContent();
}

At this point we will get a warning:
Type Safety: Unchecked Cast

Cause Analysis

The reason for the emergence of this warning, because we do not have in the List of all the objects one by one cast (type casting). If we just direct conversion of type List, it would produce unsafe types of potential risks.

For example, objects outside Bookmark If for some wrong operation, we accidentally put into the List inside. So when we operate on the Bookmark in the loop, we'll get an exception exception.

List<?> list = Arrays.asList("1", new Bookmark());
List<Bookmark> bookmarks = (List<Bookmark>) list;
for (Bookmark bookmark : bookmarks) {
    bookmark.getContent();
}
// Exception: String cannot be cast to Bookmark
Solution

By creating a new List, then remove the old one by one in the List of objects, type conversion, then add in the new List , we can successfully solve this problem.

List<?> list = payload.get("list");
List<Bookmark> bookmarkList = new ArrayList<>();
for (Object item : list) {
	bookmarkList.add((Bookmark) item);
}
for (Bookmark bookmark : bookmarkList) {
	bookmark.getContent();
}

The benefit of this is the following two points:

  1. It can be solved warning.
  2. If you have the type of problems, abnormal exception is thrown in this line, to facilitate future easy to find the cause (debug) when things go wrong.

Author still learning, if there is something wrong, please point out and contain, thank you!

Author: David Chou (Vancouver SFU computer student)

发布了14 篇原创文章 · 获赞 8 · 访问量 2211

Guess you like

Origin blog.csdn.net/vandavidchou/article/details/102545491