简体   繁体   English

为什么try-catch不会在未经检查的泛型强制转换中解决警告?

[英]Why doesn't try-catch resolve the warning in unchecked generics casts?

Consider the following MCVE : 考虑以下MCVE

public class MyClass {
    private LinkedList<Foo> myList = new LinkedList<Foo>();

    // Some irrevelant stuff which includes loading myList

    public void myMethod() {
        LinkedList<Foo> newList;

        try {
             newList = (LinkedList<Foo>) myList.clone();
        } catch (ClassCastException e) {
             // do something in case java screws up
        }
    }
}

I know that you can get rid of the warning by using @SuppressWarnings("unchecked") but why doesn't the try/catch block work? 我知道您可以通过使用@SuppressWarnings("unchecked")来消除警告,但为什么try/catch块不起作用? Is it a waste of time and energy to put the try/catch in there? try/catch放在那里是浪费时间和精力吗?

That won't work, because you are not getting a ClassCastException for this. 这不起作用,因为你没有得到ClassCastException。

The erased type of the list cannot be checked at runtime. 无法在运行时检查已清除的列表类型。

You might get a ClassCastException when you try to get something out of the List (and that turns out not to be a Foo), but the List itself is just a LinkedList (without knowing what its element types can be). 当你试图从List中获取一些东西时,你可能会得到一个ClassCastException(而事实证明它不是一个Foo),但是List本身只是一个LinkedList(不知道它的元素类型是什么)。

An instance of LinkedList<Foo> looks exactly like a LinkedList<Bar> at runtime. LinkedList<Foo>的实例在运行时看起来与LinkedList<Bar>完全相同。

The reason for the warning is that the runtime system cannot guarantee that the cast you are doing is correct (it can check the LinkedList part, but not the generic type). 警告的原因是运行时系统无法保证您正在执行的转换是正确的(它可以检查LinkedList部分,但不能检查泛型类型)。

I think that when you are explicitly casting anything, the compiler doesn't check for unchecked exceptions. 我认为,当您显式地转换任何内容时,编译器不会检查未经检查的异常。 The compiler relies on the code writer for explicit type casting. 编译器依赖代码编写器进行显式类型转换。

- Erasure is a process in which the Type Parameters and Arguments are removed from the Class within and the methods,etc. - Erasure从类内部和方法等删除 Type Parameters and Arguments的过程

- Box<String> becomes Box , this is known as Raw Type , where the Generic classes and interfaces are stripped off their Type Arguments during the Compile time, - Box<String>变为Box ,这称为Raw Type ,在编译时,Generic类和接口将从其Type Arguments中删除,

- And this is done so that during Run time a back ward compatibility can be obtained to those codes which doesn't used the Generics . -这样做是为了在Run time期间可以获得那些使用Generics代码的后向兼容性

So thats the reason this is going unchecked. 所以这就是为什么不加以控制的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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