静态与超类中定义的泛型类型

时间:2015-10-01 08:31:25

标签: java generics inheritance static-methods

我正在尝试构建一个泛型系统,它允许我创建可以调用存在于返回子类类型的抽象超类上的静态的子类。到目前为止,这有效:

public abstract class GenericsTest<T extends GenericsTest<T>> {

    @SuppressWarnings("unchecked")
    protected T createT() {
        try {
            Type supe = getClass().getGenericSuperclass();
            Type t = ((ParameterizedType) supe).getActualTypeArguments()[0];
            // This means that the type needs a default constructor.
            // Sadly there is no real way to enforce this in java.
            return (T) (Class.forName(t.toString()).newInstance());
        } catch (Exception e) {
            return null;
        }
    }

    public static <T extends GenericsTest<T>> T fetch(int key) {
        GenericsTest<T> obj = new GenericsTest<T>() {};
        T ret = obj.createT();
        // do stuff here to actually fetch/fill the object
        return ret;
    }
}

现在,通过将实现类定义为

public class GenericsTestImpl extends GenericsTest<GenericsTestImpl>

我可以致电GenericsTestImpl coolstuff = GenericsTestImpl.fetch(k);,这很酷。

然而......当我添加第二个泛型类型参数时,将最终类型定义更改为<T extends GenericsTest<T, E>, E>整个系统失败,原因有些奇怪。原始超类没有问题,但实际调用fetch()表示类型不匹配:

// Bound mismatch: The generic method fetch(int) of type GenericsTest<T,E>
// is not applicable for the arguments (int). The inferred type
// GenericsTestImpl&GenericsTest<GenericsTestImpl&GenericsTest<T,E>,Object>
// is not a valid substitute for the bounded parameter <T extends GenericsTest<T,E>>

(作为评论代码添加,因为标记吞下&lt;&gt; stuff)

新代码:

public abstract class GenericsTest<T extends GenericsTest<T, E>, E> {

    @SuppressWarnings("unchecked")
    protected T createT() {
        try {
            Type supe = getClass().getGenericSuperclass();
            Type t = ((ParameterizedType) supe).getActualTypeArguments()[0];
            // This means that the type needs a default constructor.
            // Sadly there is no real way to enforce this in java.
            return (T) (Class.forName(t.toString()).newInstance());
        } catch (Exception e) {
            return null;
        }
    }

    public static <T extends GenericsTest<T, E>, E> T fetch(int key) {
        GenericsTest<T, E> obj = new GenericsTest<T, E>() {};
        T ret = obj.createT();
        // do stuff here to actually fetch/fill the object
        return ret;
    }
}

实施:

public class GenericsTestImpl extends GenericsTest<GenericsTestImpl, String>

有没有人知道为什么附加类型搞砸了?据我所知,这确实匹配。

0 个答案:

没有答案
相关问题