Java:类型标记中的泛型类型

Bee*_*ope 9 java generics types

我有一个类,它接受一个类型标记,然后生成一个由该类型参数化的类型的对象(好吧,它比这更复杂,但这是一个简洁的例子):

public class Test {

    public static void main(String[] args) throws Exception {
        Holder<HashSet<Integer>> i = newObjectHolder(HashSet.class);  // this fails
    }

    static class Holder<T> {
        public Holder(T newInstance) {}
    }

    public static <T> Holder<T> newObjectHolder(Class<T> typeToken) throws Exception {
        Constructor<T> ctor = typeToken.getConstructor();
        return new Holder<T>(ctor.newInstance());
    }
}
Run Code Online (Sandbox Code Playgroud)

如果传递非泛型类型,这可以正常工作,如:

Holder<Integer> i = Test.newObjectHolder(Integer.class);
Run Code Online (Sandbox Code Playgroud)

但是,如果传递的类型标记是通用的,则它不起作用,如上面指示的行:

Holder<HashSet<Integer>> i = Test.newObjectHolder(HashSet.class);  // this fails
Run Code Online (Sandbox Code Playgroud)

我遇到了问题,但有解决方案吗?我可以在代码中添加@SuppressWarnings("unused")newObject,如果它不降低安全性的话.直观地说,似乎newObject应该能够使一个有效的转换,我们知道擦除泛型类型的一个"新"对象与任何其他对象相同,我们还没有T在该方法中使用.

Bee*_*ope 5

所以,害羞地回答我自己的问题......

我找不到任何方法来做到这一点Class<?>,但这种称为超级类型令牌的神奇技术似乎效果很好。这是更新后的代码:

public class Test {

    static class A {}
    static class B extends A {}


    public static void main(String[] args) throws Exception {
        Holder<HashSet<Integer>> i = newObjectHolder(new TypeReference<HashSet<Integer>>() {});  // works
        Holder<A> j = newObjectHolder(new TypeReference<A>() {});  // works
        Holder<A> k = newObjectHolder(new TypeReference<B>() {});  // works
        Holder<B> l = newObjectHolder(new TypeReference<A>() {});  // doesn't compile (good)
    }

    static class Holder<T> {
        public Holder(T newInstance) {}
        T get() { return null; }
    }

    public static <T,U extends TypeReference<? extends T>> Holder<T> newObjectHolder(U typeToken) throws Exception {
        T obj = typeToken.newInstance();
        return new Holder<T>(obj);
    }
}
Run Code Online (Sandbox Code Playgroud)

代码在这里TypeReference给出,尽管我怀疑 Guice 也能正常工作(但它没有 newInstance 代码,你必须实现它)。 TypeLiteral