简体   繁体   English

未经检查的类型转换与不可转换类型

[英]Unchecked cast vs Inconvertible Types

I discovered a bug in some old code which obviously will never work. 我在一些旧代码中发现了一个错误,该错误显然永远不会起作用。 However, it is a runtime exception rather than a compile time exception. 但是,它是运行时异常,而不是编译时异常。 I swapped out my custom class for a standard Java class and I get a compile error. 我将自定义类替换为标准Java类,但出现编译错误。

What is the difference that causes one to be a Unchecked cast (runtime exception) while the other is an Inconvertible Types (compile exception)? 有什么区别导致一个是Unchecked强制转换(运行时异常),而另一个是Inconvertible Types(编译异常)?

GenTest.java GenTest.java

import java.util.Collection;
import java.util.Optional;

public class GenTest {
    public static void main(String[] args) {
        try {
            MyClass<Integer> a = new MyClass<>(10);
            // This generates a warning but compiles, then fails at runtime
            Collection<MyClass<Integer>> runtimeFail = (Collection<MyClass<Integer>>) a;
        } catch (ClassCastException cce) {
            cce.printStackTrace();
            System.out.println("encountered expected runtime error");
        }

        Optional<Integer> b = Optional.of(10);
        // This generates a compile time exception
        //Collection<Optional<Integer>> compileFail = (Collection<Optional<Integer>>) b;
    }
}

MyClass.java MyClass.java

public class MyClass<T> {
    T value;

    public MyClass(T value) {
        this.value = value;
    }
}

Tom pointed me to the duplicate which answered the question, see ClassCastException vs. "cannot cast" compilation error 汤姆将我指向回答问题的重复项,请参见ClassCastException与“无法转换”编译错误

TO re-hash, I changed MyClass to final and it gave a compile time error. 为了进行重新哈希处理,我将MyClass更改为final,并给出了编译时错误。 Optional is also a final class. 可选的也是最后一堂课。

Thanks 谢谢

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

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