Puiu Ioan
Puiu Ioan

Reputation: 89

Get the class for a generic collection without using an instance

Iwould like to do something like the following:

public class Test {
    public static void main(String[] args) {
        Map<String, Set<String>> map = new HashMap<String, Set<String>>();
        map.put("key1", new HashSet<String>());

        Set<String> theSet = getObjectAs(map, ***Set<String>.class***);
    }

    private static <T> T getObjectAs(Object object, Class<T> cls){
        return cls.cast(object);
    }
}

But this doesn't work, I can't get the class object out of that Set using .class (see in bold) because it is parameterized.

I want to make that method to return a Set who's type may vary (it won't always be a set of Strings) but which I know and I can give as a parameter.

Is there another way of doing something like this?

Upvotes: 0

Views: 285

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198123

The only way you can possibly do this is to accept that you need to do unsafe casts. There is no such thing as Set<String>.class, because it would be exactly equal, in every respect, to Set.class.

The only other thing you might be able to do is use one of the "generic Class" types from a library somewhere, like Guava's TypeToken, but this wouldn't let you get around the need for unsafe casts -- it would only let you specify it with generics. Guava's TypeToInstanceMap works similarly.

Upvotes: 1

Related Questions