6

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

8
  • 3
    What do you want to achieve? It's hard to answer your question without knowing that... Commented Feb 6, 2013 at 10:07
  • Class can be a nasty beast. 5th option: new Field<Iterable<Object>>(List.class) ('warning: unchecked assignment'). Commented Feb 6, 2013 at 10:11
  • possible duplicate of Class object of generic class (java) Commented Feb 6, 2013 at 10:18
  • @AndersR.Bystrup It's an example that reflects an issue I'm facing with the custom objects of the project I'm working on. So I'm afraid I can't be more specific, sorry... Commented Feb 6, 2013 at 10:33
  • @akaIDIOT With your solution, I'm not getting a warning but an error: The constructor Main.Field<Iterable<Object>>(Class<List>) is undefined. Commented Feb 6, 2013 at 10:34

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I haven't seen type parameters on a constructor before, but nice solution
This is really awesome, I had never noticed that you could infer generic types to constructors. That said, I don't really understand why this solution doesn't cause the same error as in 2...
@sp00m Pretty sure it abuses a compiler bug ( see stackoverflow.com/q/11570215/774444 ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.