User1
User1

Reputation: 41163

How do I specify a Class variable that contains a generic

Here's a sample that should explain my problem:

public class Scratch {
    public <T> Set<T> method(Class<T> clazz){return null;}

    public static void main(String[] args){
        Scratch s=new Scratch();
        Set<List<String>> list=s.method(List.class); //Gives error here.  How do I say List<String>.class?
    }
}

I really want to say List<String>.class for the clazz variable above, but that not the appropriate syntax. Am I just using generics in a wrong way?

Upvotes: 2

Views: 84

Answers (2)

irreputable
irreputable

Reputation: 45433

It's a limitation of the language and the standard library.

Workaround is to simply cast it brutely

(Class<List<String>>)(Class)List.class

Upvotes: 2

User1
User1

Reputation: 41163

Using Class<?> clazz worked.

Here's the modified code:

public class Scratch {
    public <T> Set<T> method(Class<?> clazz){return null;}

    public static void main(String[] args){
        Scratch s=new Scratch();
        Set<List<String>> list=s.method(List.class); 
        Set<Map<String,String>> map=s.method(Map.class);
    }
}

Thanks to @Traroth for pushing me in the right direction. I modified his answer to support a truly generic structure beyond just Lists.

EDIT: I'm still not completely happy with the answer above because you can do something bad. Consider this example:

public class Scratch {
    public <T> Set<T> method(Class<?> clazz){return null;}

    public static void main(String[] args){
        Scratch s=new Scratch();
        Set<List<String>> list=s.method(Map.class); //Should've passed List.class, but the compiler doesn't care.
        Set<Map<String,String>> map=s.method(Map.class);
    }
}

Everything compiles and I will likely get some runtime errors (depending on my implementation). Any other advice is appreciated...

Upvotes: 0

Related Questions