bartlaarhoven
bartlaarhoven

Reputation: 845

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?

Upvotes: 0

Views: 99

Answers (3)

GhostCat
GhostCat

Reputation: 140623

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

Upvotes: 2

Thilo
Thilo

Reputation: 262834

There is no Class<Set<String>> object.

Generic types are erased at runtime, so there is only an instance of Class<Set> (namely Set<?>.class) shared by all the Class<Set<?>>. There is no way to get back to String from this object.

For this very reason, your JSON library has a TypeRef class to capture the generic type information. You just use that instead of Class.

Upvotes: 0

Markus Mitterauer
Markus Mitterauer

Reputation: 1610

You mean, how to define that the return type depends on the parameter type?

Try this:

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

Upvotes: -1

Related Questions