gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:24:51 25 4
gpt4 key购买 nike

在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 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) {

}
}

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

关于java - 我可以强制构造函数对其泛型类型进行更严格的限制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55259209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com