2015-10-06 28 views
3

我有一个类ListCreator<T>和一个静态方法collectFrom(),它构造了这个类的一个实例。 collectFrom()有一个参数List l,我想参数化ListCreator的返回实例与指定的List是相同的类型。如何通过与给定对象相同的类型来参数化对象?

理想我想这样的事情:

public static ListCreator<T> collectFrom(List<T> l) { 
    return new ListCreator<T>(l); 
} 

但这是不可能的,所以我坚持这一点:

public class ListCreator<T> { 

    List<T> l; 

    public ListCreator(List<T> l) { 
     this.l = l; 
    } 

    public static ListCreator collectFrom(List l) { 
     return new ListCreator(l); 
    } 
} 

有没有更好的解决办法?

回答

6

泛化你的方法通过引入在其定义的类型参数:

public static <T> ListCreator<T> collectFrom(List<T> l) { 
    return new ListCreator<T>(l); 
} 

事实上,在class ListCreator<T> {声明的类型参数有这个方法没有任何意义,因为它是static(见Static method in a generic class?)。

+2

它对构造函数和成员变量有意义。 –

+0

@JBNizet是的我的意思是这个方法。感谢您指出。 – manouti

相关问题