Is it safe from my general method?

I have code in my project that looks like this:

public interface Bar<T extends Foo<?>> {
 //...
}

public class MyFoo implements Foo<String> {
    private List<Bar<Foo<String>> barFoo = ...

    public <U extends Foo<String>> boolean addBar(Bar<? extends U> b) {
        barFoo.add((Bar<Foo<String>>) b); //safe cast?
    }

}

Eclipse gives a warning to translate in addBarthat the cast is unsafe. Nevertheless, can I correct the assumption that the cast will not be selected taking into account the restrictions that I have imposed on the type parameters, and therefore casting is really safe?

+5
source share
3 answers

Not in general.

, Bar void get(T value), Foo<String>, MyFoo YourFoo. , addBar Bar<MyFoo>. : U= Foo<String>, , Bar<MyFoo> Bar<? extends U>. Bar<Foo<String>>.

, Bar , T , . , void process(T value). , , T= MyFoo, process(MyFoo value). Bar<Foo<String>>, YourFoo. .

, , , , barFoo List<? extends Bar<? extends Foo<String>>.

+6

. Eclipse .

, MyFoo, Foo, Bar<MyFoo<String>> Bar myMethod(Foo x), myMethod(MyFoo x), .

+2

, , U extends Foo<String>, () , Bar<U> Bar<Foo<String>>. , Bar<U> Bar<Foo<String>>, , .. U Foo<String>.

, , () List<String> List<Object>, , . List<String> List<? extends Object>, List<Object>. (, Comparable<T>: Comparable<String> " String, Comparable<Object> " Object ". , Comparable<String> Comparable<Object>.)

[& hellip;] [& hellip;], ?

, . Eclipse , , , . , :

final Object o = Integer.valueOf(7);
final String s = (String) o;

absolutely safe because the throw throws an exception. But this code:

final List<?> wildcardList = new ArrayList<Integer>(Integer.valueOf(7));
final List<String> stringList = (List<String>) wildcardList;

is unsafe because the runtime does not have the ability to check the cast (due to erasure), so it will not throw an exception, although this is not true: stringListnow it is List<String>whose first element is of type Integer. (What happens, at some point later, you may get spontaneous ClassCastExceptionwhen you try to do something with this element.)

0
source

All Articles