JAVA和泛型类型问题

时间:2013-02-06 10:02:35

标签: java generics

我遇到了泛型类型的问题:

public static class Field<T> {

    private Class<? extends T> clazz;

    public Field(Class<? extends T> clazz) {
        this.clazz = clazz;
    }

}

public static void main(String[] args) {

    // 1. (warning) Iterable is a raw type. References to generic type Iterable<T> should be parameterized.
    new Field<Iterable>(List.class);

    // 2. (error) The constructor Main.Field<Iterable<?>>(Class<List>) is undefined.
    new Field<Iterable<?>>(List.class);

    // 3. (error) *Simply unpossible*
    new Field<Iterable<?>>(List<?>.class);

    // 4. (warning) Type safety: Unchecked cast from Class<List> to Class<? extends Iterable<?>>.
    new Field<Iterable<?>>((Class<? extends Iterable<?>>) List.class);

}

1.和4.之间的最佳解决方案是什么(顺便说一下,还是其他任何一种方法)?

1 个答案:

答案 0 :(得分:5)

public class Field <T> {
    private Class <? extends T> clazz;

    public <TT extends T> Field (Class <TT> clazz) {
        this.clazz = clazz;
    }

    public static void main (String [] args) {
        new Field <Iterable <?>> (List.class);
    }
}