我可以强制构造函数对其泛型类型进行更严格的限制吗?

Can I force a constructor to put a stricter bound on its generic type?

在java中,泛型类有构造函数来构造一些泛型类型的实例。这很简单,构造函数的调用者可以指定范围内的任何类型。

是否可以有一个构造函数对该泛型类型设置更严格的界限?
例如,有一个强制泛型类型为 String.

的构造函数
public class GenericClass<T extends Serializable> {
    public GenericClass() {
        // normal constructor
    }

    public GenericClass(String argument) {
        // Can I force this constructor to construct a `GenericClass<String>`?
    }
}

// The first constructor can have any type
GenericClass<String> stringInstance = new GenericClass<>();
GenericClass<Integer> intInstance = new GenericClass<>();

// The second constructor is limited to `GenericClass<String>`
stringInstance = new GenericClass<>("with generic type String is okay");
intInstance = new GenericClass<>("with other generic type is not okay");

由于类型不兼容,我希望最后一行失败。

这可能吗?

导致最后一行失败的一种方法是:

public class GenericClass<T extends Serializable> {
    public GenericClass() {
        // normal constructor
    }

    public GenericClass(T argument) {

    }
}

但显然这并不能阻止人们打电话给 new GenericClass<>(1)

或者,你可以写一个工厂方法ofString:

public static GenericClass<String> ofString(String s) {
    GenericClass<String> gc = new GenericClass<>();
    // do stuff to gc
    return gc;
}
public GenericClass(String argument)

问题是编译器应该如何知道 StringT?参数和泛型类型参数之间没有link,无法指定。你可以使用

public GenericClass(T argument)

并用

构造它
new GenericClass<>("foo");

但这将允许 GenericClass 用任何类型的对象实例化。

你可以使用继承大致实现你想要的,尽管你需要引入第二个 class:

class GenericClass<T extends Serializable> {
    public GenericClass() {

    }
}

class StringClass extends GenericClass<String> {
    public StringClass(String argument) {

    }
}

如果您想避免使用继承,您可以引入一个接口并让两个 class 都实现它。这就是我要做的。