为什么HashSet对象的反序列化给我的代码中未检查的警告? | Java的| IntelliJ IDEA的|

问题描述 投票:3回答:1

在我的代码,当我尝试反序列化HashSet对象它给了我这样的警告:

Unchecked assignment:'java.util.HashSet' to'java.util.HashSet<java.lang.Integer>
Inspection info: Signals places where an unchecked warning is issued
by the compiler, for example:
 void f(HashMap map) {  map.put("key", "value"); }
Hint: Pass -Xlint:unchecked to javac to get more details.

这是一个重要的警示?或者我应该使用@SuppressWarnig?

我怎样才能消除这个警告?请帮帮我的家伙,我在Java中新

我的代码是:

public class Main{
    public static void main(String[] args){
    HashSet<Integer> number=new HashSet<>();
    Scanner input=new Scanner(System.in);
    int option;
    while(true){
        System.out.println("1. add 2. display 3. save 4. load 5. exit");
        option=input.nextInt();
        if(option==1){
            System.out.println("Adding : "+ number.add(1));
            System.out.println("Adding : " + number.add(2));
        }else if(option==2){
            System.out.println("Set is : "+ number);
        }else if(option==3){
            try{
                FileOutputStream fos=new FileOutputStream("data.bin");
                ObjectOutputStream oos=new ObjectOutputStream(fos);
                oos.writeObject(number);
                oos.close();
                fos.close();
            }catch(IOException e){
                e.getMessage();
            }
        }else if(option==4){
            try{
                FileInputStream fis=new FileInputStream("data.bin");
                ObjectInputStream ois=new ObjectInputStream(fis);
                number=(HashSet)ois.readObject(); // this line give me warning
            }catch(IOException | ClassNotFoundException e){
                e.getMessage();
            }
        }else if(option==5){
            break;
        }
    }
}
}
java generic-collections
1个回答
3
投票

有没有(易)的方式来编写代码,这样你就不会得到这个警告。它是非关键的,你也许可以忽略它。

为什么会发生?

泛型是编译器的凭空想象。你唯一的字节存储了您保存一个HashSet对象的序列化流,它不存储<Integer>部分,也不可​​能,因为这些信息不再出现在运行时。

当存储加载从序列化流回到number变量中的对象,Java有不知道是否在事实上HashSet中只包含Integer实例,并在运行时不选中该项。如果它包含例如字符串,就这样吧,以后你会得到一个ClassCastException如果是这样的情况。

警告具体是指:“好吧,你断言,这HashSet的,你刚刚从序列化系统得到了仅包含整数有用于javac没有编译时的方式来验证这一点,而这个转换不会生成运行时代码要么做到这一点。因此,我们只是通过你说会这么,让我们希望,你是对的!如果不是,将在怪异的地方后发生的ClassCastExceptions。”

我怎样才能避免呢?

一种方法是通过首先分配给类型HashSet<?>,然后循环的变量,检查每个值,如果它是一个整数,如果是把它放在number,如果没有出口与一个适当的错误消息的方法。铸造一组个别成员是可能的,没有得到警告..但现在你花费额外的循环。

一个更好的解决方案是不建在序列化机制Java的使用摆在首位。它是复杂的,往往会借给自己的安全问题,这是很难应付不断扩大的需求(这是很难改变的版本或负载/它从其他语言编写),它不是人类可读的,它是空间效率不高。

尝试例如Jackson序列化你的对象。

© www.soinside.com 2019 - 2024. All rights reserved.