本文介绍了泛型和匿名类(错误或功能?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个代码没有编译,因为'A'表达式。有趣的是:在一个表达式中,期望

This code not compiles, because of 'A' expression. It's interesting thing: in A expression expected

List<Foo>

泛型类型,但得到了

List<anonymous Foo> 

(根据编译器)。它是一个jdk错误或功能?

(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() { }
    });

当你有一个明确的对象被调用时,它看起来更好(恕我直言) this。< Foo> bar(...)

It looks better (IMHO) when you have an explicit object that the method's being called on, e.g. this.<Foo>bar(...).

这篇关于泛型和匿名类(错误或功能?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 13:33