【问题标题】:Java unchecked or unsafe operations messageJava 未经检查或不安全的操作消息
【发布时间】:2013-05-13 02:40:41
【问题描述】:

BlueJ 中编译 Java 类时出现以下错误。

AuctionManager.java uses unchecked or unsafe operations.

仅当以下反序列化代码在我的一个函数中时才会显示此错误:

try {
  ObjectInputStream in = new ObjectInputStream(new FileInputStream(Filename));
  ArrayList<AuctionItem> AuctionList = (ArrayList<AuctionItem>) in.readObject();
  in.close();
}
catch (Exception e) {
  e.printStackTrace();
}

能否请我提供一些关于为什么显示此错误的信息,以及使用反序列化代码没有错误的一些帮助。

【问题讨论】:

    标签: java serialization deserialization compiler-warnings unchecked-exception


    【解决方案1】:

    首先你得到的消息不是错误,是警告吗?它不会阻止您的程序编译或运行。

    至于出处,就是这一行:

    ArrayList&lt;AuctionItem&gt; AuctionList = (ArrayList&lt;AuctionItem&gt;) in.readObject();

    由于您将对象(readObject 返回 Object)转换为参数化类型(ArrayList&lt;AuctionItem&gt;)。

    【讨论】:

    • 修复代码以使警告不显示的最佳方法是什么?
    【解决方案2】:

    user2351151:你可以这样做,因为警告不显示:

    ArrayList tempList; // without parameterized type 
    try {
      ObjectInputStream in = new ObjectInputStream(new FileInputStream(Filename));
      tempList = (ArrayList) in.readObject();
      for (int i = 0; i < tempList.size(); i++) {
        AuctionList.add(i, (AuctionItem)tempList.get(i)); // explict type conversion from Object to AuctionItem
      }
      in.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    

    你必须用显式类型转换重写ArrayList(你可以使用没有参数化类型的临时ArrayList)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多