简体   繁体   中英

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.

What is the difference that causes one to be a Unchecked cast (runtime exception) while the other is an Inconvertible Types (compile exception)?

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

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

TO re-hash, I changed MyClass to final and it gave a compile time error. Optional is also a final class.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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