简体   繁体   中英

Unchecked cast warning in code

My code:

 private List<Day> readDays(File file) {
        List<Day> days = new ArrayList<>();
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            days.addAll((List<Day>) in.readObject());
        } catch (IOException | ClassNotFoundException e) {
            Logger.logError(LOG_TAG, e);
        }
        return days;
    }

Unchecked cast problem in this code

 days.addAll((List<Day>) in.readObject());

And this is a problem, in some cases the app crashes.

if your problem is cast object; you can define a convertor to convert your object to your class and handle exceptions.

if your stream return json string, You can use ObejctMapper and convert json string to your class as follow method by using jackson library:

    //create ObjectMapper instance
    ObjectMapper objectMapper = new ObjectMapper();

    //convert json string to object
    Day day = objectMapper.readValue(jsonData, Day.class); 

   // use day class now

so converting object, depend on your file data format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM