如何通过与给定对象相同的类型参数化对象?

Yod*_*oda 3 java generics

我有一个类ListCreator<T>和一个静态方法collectFrom()来构造这个类的实例.collectFrom()有一个参数List l,我想参数化返回的实例ListCreator与指定的类型相同List.

理想情况下,我想要这样的东西:

public static ListCreator<T> collectFrom(List<T> l) {
    return new ListCreator<T>(l);
}
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有更好的解决方案吗?

man*_*uti 6

通过在其定义中引入type参数来通用化您的方法:

public static <T> ListCreator<T> collectFrom(List<T> l) {
    return new ListCreator<T>(l);
}
Run Code Online (Sandbox Code Playgroud)

实际上,声明的类型参数class ListCreator<T> {对此方法没有意义,因为它是static(参见泛型类中的静态方法?).

  • 它对构造函数和成员变量有意义. (2认同)