Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA and generic types issue

Tags:

java

generics

I'm facing an issue with generic types:

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);

}

What's the best solution between the 1. and the 4. (or any other one by the way)?

like image 406
sp00m Avatar asked Feb 06 '13 10:02

sp00m


1 Answers

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);
    }
}
like image 67
Mikhail Vladimirov Avatar answered Oct 10 '22 04:10

Mikhail Vladimirov