定义泛型 objects

Defining generic objects

接着我上一个问题 :

我有一个 class 像这样:

public class nVector<T extends nVector<?>> {

    int i;

    public T add(T a) {

    }

}

并希望发生以下情况:

public T add(T a) {
    T b = this.clone();
    b.i += a.i;
    return b;
}

然而,Generic 类型的实例化 T 是不允许的。然而,我可以轻松地在我的论点中包含一个 T 的实例。

我这样做是因为我有多个 T 类型的 children,它们继承了 nVector 的所有方法并在 'enclosed environment' 中作用于它们自己。 (即他们只将自己的类型作为参数,而不是其他children)

有什么办法可以解决这个问题吗?问题是,我 到 return 类型 T 的东西,而不是 nVector<?>.

您可以将 Class<T> 传递给 nVector 构造函数。然后使用 cls.newInstance()。像,

public class nVector<T extends nVector<?>> {
    Class<T> cls;
    int i; // <-- default value 0. Should probably be set in the constructor
           //     or with a setter method.
    public nVector(Class<T> cls) {
        this.cls = cls;
    }

    public T add(T a) {
        T b = null;
        try {
            b = cls.newInstance();
            b.i = this.i + a.i; // <-- equivalent, thx @LukeLee
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return b;
    }
}

当然,如果您只需要 T 到 return - 您可以 return a;