在Java中围绕类型擦除设计构造函数 [英] Designing constructors around type erasure in Java

查看:63
本文介绍了在Java中围绕类型擦除设计构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天,我正在设计一个Java类,希望将其引入各种通用类型的列表:

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?

推荐答案

我很想知道针对此问题的一个好的解决方法。

I would love to know a neat fix for this issue.

我经常遇到相同的问题,通常我会通过引入一个虚拟参数(例如 Void )到构造函数,这当然不是最优雅的解决方案,但是到目前为止我所知道的最好的解决方案。

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.

这篇关于在Java中围绕类型擦除设计构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆