首页 > 解决方案 > 令牌“sList”上的语法错误,此令牌后应为 VariableDeclaratorId ....?如何解决这个问题..?

问题描述

对象反序列化 sList无法解析为类型如何解决这个问题

public static ArrayList<Student> deSerialize(String filename) {
    ArrayList<Student> sList = new ArrayList<Student>();

    try {
        FileInputStream fiStream = new FileInputStream(filename);
        ObjectInputStream inStream = new ObjectInputStream(fiStream);

        @SuppressWarnings("unchecked")
        sList = (ArrayList<Student>) inStream.readObject();
        fiStream.close();
        inStream.close();
    } catch (Exception e) {
        System.out.println(e);
    }
    return sList;
}

查看错误的屏幕截图

标签: java

解决方案


在 Java 中,您不能将注释 ( @...) 放在随机的代码段上。
只需移动@SuppressWarnings("unchecked")到方法声明之上:

 @SuppressWarnings("unchecked")
 public static ArrayList<Student> deSerialize(String filename) {
     ArrayList<Student> sList = new ArrayList<Student>();
     try {
         FileInputStream fiStream = new FileInputStream(filename);
         ObjectInputStream inStream = new ObjectInputStream(fiStream);
         
         sList = (ArrayList<Student>) inStream.readObject();
         fiStream.close();
         inStream.close();
     } catch (Exception e) {
         System.out.println(e);
     }
     return sList;
 }

确切地说,您可以放置​​的地方数量有限@SuppressWarnings,它们都列在@Target文档的注释中

例如,因为它是一个局部变量声明,你可以 - 然而 - 写:

public static ArrayList<Student> deSerialize(String filename) {
    @SuppressWarnings("unchecked")
    ArrayList<Student> sList = new ArrayList<Student>();
}

在这种情况下,它是无用的,但合法的。


推荐阅读