首页 > 解决方案 > 我可以强制构造函数对其泛型类型进行更严格的限制吗?

问题描述

在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");

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

这可能吗?

标签: javagenericsconstructortype-bounds

解决方案


public GenericClass(String argument)

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

public GenericClass(T argument)

并用

new GenericClass<>("foo");

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

您可以使用继承大致实现您想要的,但您需要引入第二个类:

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

    }
}

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

    }
}

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


推荐阅读