在 Java 中围绕类型擦除设计构造函数

发布于 2024-08-29 22:31:11 字数 480 浏览 10 评论 0原文

昨天,我正在设计一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

栩栩如生 2024-09-05 22:31:11

我很想知道这个问题的巧妙解决方案。

我经常遇到同样的问题,我通常通过向构造函数引入一个虚拟参数(例如 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.

简美 2024-09-05 22:31:11

请注意,可以在带有擦除的通用参数上添加方法重载,尽管通配符会使它变得更加困难。

我建议使用基于类型解释的名称的创建方法。 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).

对风讲故事 2024-09-05 22:31:11

不同的解决方案:

1) 使用选项卡

class TheClass
{
 TheClass(String[] strings)   {}
 TheClass(Object[] others) {}
}

2) 使用泛型

class TheClass<P>
{
 TheClass(P generic) {}
}

Differents solutions :

1) with tabs

class TheClass
{
 TheClass(String[] strings)   {}
 TheClass(Object[] others) {}
}

2) with generics

class TheClass<P>
{
 TheClass(P generic) {}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文