bartlaarhoven bartlaarhoven - 2 months ago 9
Java Question

Get class based on variable generic class

I'm trying to get the solution to achieve the following:

public final static <T> Class<Set<T>> getSetClass(Class<T> cls) {
...
}


Where
cls
is for example
String.class
and the method then returns the
Class<Set<String>>
object. But of course, as
cls
is variable, it could also get
Boolean.class
and then return a
Class<Set<Boolean>>
object.

How can I achieve this?

Answer

This works for me:

@SuppressWarnings("unchecked") 
public <T> Class<Set<T>> getSetClass(Class<T> cls) { 
  Set<T> set = new HashSet<>(); 
  return (Class<Set<T>>) set.getClass();
}

Well, it compiles; how useful it is to solve your "real" problem; I can't tell yet. And obviously; that cls parameters goes unused here.

But it does something:

@Test
public void test() {
    Class<Set<Integer>> setClass = new PartitionPropertiesTest().getSetClass(Integer.class);
    System.out.println("whatever: " + setClass);
}

prints:

whatever: class java.util.HashSet
Comments