0

我想做类似以下的事情:

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);
    }
}

但这不起作用,我无法使用 .class 将类对象从该 Set 中取出(参见粗体),因为它是参数化的。

我想让该方法返回一个类型可能会有所不同的 Set(它并不总是一组字符串),但我知道并且可以将其作为参数提供。

还有另一种方法可以做这样的事情吗?

4

1 回答 1

1

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.

于 2013-01-24T20:43:14.750 回答