Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and anonymous classes (bug or feature?)

Tags:

java

generics

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
    }
}
 
like image 518
whiter4bbit Avatar asked Nov 24 '25 09:11

whiter4bbit


1 Answers

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(...).

like image 83
Andrzej Doyle Avatar answered Nov 26 '25 22:11

Andrzej Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!