直接跟随@SuppressWarnings的Eclipse错误("未选中")

sty*_*972 3 java eclipse generics android

我似乎遇到了一些问题,这个问题是从文件反序列化包含MyObject类型的ArrayList得到的警告.我得到的错误信息来自该行

objects = (ArrayList<MyObject>) ois.readObject();
Run Code Online (Sandbox Code Playgroud)

它写道:

Type safety: Unchecked cast from Object to ArrayList<MyObject>
Run Code Online (Sandbox Code Playgroud)

在我将@SuppressWarnings("unchecked")应用于特定警告后,它表示我的对象对象无法解析为某种类型.

ArrayList<MyObject> objects;
try {
    FileInputStream fis = new FileInputStream(new File("myfile.txt"));
    ObjectInputStream ois = new ObjectInputStream(fis);
    @SuppressWarnings("unchecked")
    objects = (ArrayList<MyObject>) ois.readObject(); //Getting 'objects cannot be resolved to a type'
    fis.close();
}

catch (Exception e) {
    objects = new ArrayList<MyObject>();
}
Run Code Online (Sandbox Code Playgroud)

这很奇怪,因为如果我将@SuppressWarnings("unchecked")应用于整个方法,那么错误就会消失.此外,IS发生在多台机器,而不仅仅是一个设置.

当我只抑制错误的一个实例时,是否有人对正在发生的事情有任何见解使得此错误出现?

hom*_*ome 6

@SupressWarnings("unchecked")只能应用于declariation的对象,这将工作:

@SuppressWarnings("unchecked")
ArrayList<String> objects = (ArrayList<String>) ois.readObject();
Run Code Online (Sandbox Code Playgroud)

......但可能无法解决您的问题.其原因可以在JDK源代码中找到.在@Target关于该注解@SupressWarnings注解定义所允许的位置:

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
Run Code Online (Sandbox Code Playgroud)