在 Java 中围绕类型擦除设计构造函数
昨天,我正在设计一个 Java 类,我想用各种泛型类型的列表来初始化它:
TheClass(List<String> list) {
...
}
TheClass(List<OtherType> list) {
...
}
这不会编译,因为构造函数具有相同的擦除。
我只是使用按名称区分的工厂方法:
public static TheClass createWithStrings(List<String> list)
public static TheClass createWithOtherTypes(List<OtherType> list)
这并不是最佳选择,因为没有一个明显的位置可以提供用于创建实例的所有不同选项。
我试图寻找更好的设计理念,但结果却出人意料地少。围绕这个问题进行设计还有哪些其他模式?
Yesterday, I was designing a Java class which I wanted to be initalized with Lists of various generic types:
TheClass(List<String> list) {
...
}
TheClass(List<OtherType> list) {
...
}
This will not compile, as the constructors have the same erasure.
I just went with factory methods differentiated by their names instead:
public static TheClass createWithStrings(List<String> list)
public static TheClass createWithOtherTypes(List<OtherType> list)
This is less than optimal, as there isn't a single obvious location where all the different options for creating instances are available.
I tried to search for better design ideas, but found surprisingly few results. What other patterns exist for designing around this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我很想知道这个问题的巧妙解决方案。
我经常遇到同样的问题,我通常通过向构造函数引入一个虚拟参数(例如
Void
)来解决它,这当然不是最优雅的解决方案,但却是我所知道的最好的解决方案到目前为止。I would love to know a neat fix for this issue.
I encounter the same problem often, and I usually fix it by just introducing a dummy parameter (such as
Void
) to the constructor, which is of course not the most elegant fix, but the best one I know of so far.请注意,可以在带有擦除的通用参数上添加方法重载,尽管通配符会使它变得更加困难。
我建议使用基于类型解释的名称的创建方法。
String
本身没有多大意义。createWithThingNames
,或者其他什么。一些静态类型语言根本没有方法重载(故意)。
Note, it would be possible to add method overloading on generic arguments with erasure, although wildcards would make it more difficult.
I would suggest using creation method with a name based on the interpretation of the types.
String
by itself doesn't have much meaning.createWithThingNames
, or something.Some statically-typed languages do not have method overload at all (deliberately).
不同的解决方案:
1) 使用选项卡
2) 使用泛型
Differents solutions :
1) with tabs
2) with generics