Generics and anonymous classes (bug or function?)

This code does not compile due to the expression 'A'. This is interesting: in the expression A, the expected

List<Foo>
generic type but got
List<anonymous Foo> 
(according to the compiler). Is this a bug or a jdk function?
 
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
    }
}
 
+3
source share
4 answers

The third option, because I like the syntax, and I think that it is not used enough (and probably not so well known), is to explicitly define the general parameter of 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 calling the method, for example. this.<Foo>bar(...).

+5
source

, . , bar . , List<anonymous type>. Foo ( Foo - ), List<Foo>.

, :

List<? extends Foo> f = bar(new Foo(){
            public void doFoo() { }
        });

List<Foo> f = bar((Foo) new Foo(){
            public void doFoo() { }
        });

, , :

List<Object> objects = bar("hello"); // Won't compile

Object x = "hello";
List<Object> objects = bar(x); // Will compile

, , .

+4

, :

new Foo() {
  public void doFoo() { }
}

. . :

List<Foo> f = bar((Foo)new Foo(){ //A
  public void doFoo() { }
}); //don't compiles
0
package theBestTrick;

import java.util.ArrayList;
import java.util.List;

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

        System.out.println(new Foo(){ //A
            public void doFoo() { }
        }.getClass());//class theBestTrick.GenericsTest$1 <- THAT WHY !!! 

        Foo fooImpl = new Foo(){
            public void doFoo() { }
        };

        List<Foo> f2 = bar(fooImpl); //compiles
    }
}

, , .

, -, , underhood;)


    class FooImpl implements Foo{
        public void doFoo() { }
    }

    List<FooImpl> f3 = bar(new FooImpl()); //compiles
    List<FooImpl> f4 = bar(new FooImpl(){{
        System.out.println("I'm anonymous inner class");}}
    ); // not compiles

When you use the double bracket, you get the same compilation errors.

0
source

Source: https://habr.com/ru/post/1721382/


All Articles