This code not compiles, because of 'A' expression. It's interesting thing: in A expression expected
List<Foo> generic type, but got List<anonymous Foo> (according compiler). Is it a jdk bug or feature?
interface Foo{ void doFoo(); }
public class GenericsTest {
public static<V> List<V> bar(V v){ return new ArrayList<V>();}
public static void main(String[] args) {
List<Foo> f = bar(new Foo(){ //A
public void doFoo() { }
}); //don't compiles
Foo fooImpl = new Foo(){
public void doFoo() { }
};
List<Foo> f2 = bar(fooImpl); //compiles
}
}
A third option, because I like the syntax and I think it's underused (and probably not that well known), is to explicitly specific the generic parameter on the method call, as follows:
List<? extends Foo> f = <Foo>bar(new Foo(){
public void doFoo() { }
});
It looks better (IMHO) when you have an explicit object that the method's being called on, e.g. this.<Foo>bar(...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With