java - 我可以强制构造函数对其泛型类型进行更严格的限制吗?
问题描述
在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)
问题是编译器应该如何知道这String
是T
?参数和泛型类型参数之间没有联系,也无法指定一个。你可以使用
public GenericClass(T argument)
并用
new GenericClass<>("foo");
但这将允许GenericClass
使用任何类型的对象进行实例化。
您可以使用继承大致实现您想要的,但您需要引入第二个类:
class GenericClass<T extends Serializable> {
public GenericClass() {
}
}
class StringClass extends GenericClass<String> {
public StringClass(String argument) {
}
}
如果您想避免使用继承,您可以引入一个接口并让两个类都实现该接口。这就是我要做的。
推荐阅读
- python - ImageGrid - set_ylabel 被图截断
- c# - WCF XML 信息未显示在实时服务器上
- sql - 如何使用 Spark-SQL 在点击流数据集中计算每个用户每分钟的唯一会话 ID?
- python - 读取行之间带有 \n 的 txt 文件
- html - 当缺少 id="" 时,如何从 VBA 获取 IE 的 DOM 中的 HTML 按钮引用?
- ubuntu - Dyno 元数据未显示在“env”输出中
- flask - 烧瓶登录:AttributeError:“用户”对象没有属性“is_active”
- networking - 我可以同时训练两个网络,一个包含另一个网络的网络吗?
- reactjs - 为什么 web Worker 的 import axios 不起作用?
- python - 将嵌套列表和元组列表转换为字典python