简体   繁体   English

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

[英]Designing constructors around type erasure in Java

Yesterday, I was designing a Java class which I wanted to be initalized with Lists of various generic types: 昨天,我正在设计一个Java类,我希望通过各种泛型类型的列表进行初始化:

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. 我很想知道这个问题的一个简洁的解决方案。

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. 我经常遇到同样的问题,我通常只是通过向构造函数引入一个虚拟参数(例如Void )来修复它,这当然不是最优雅的修复,但是到目前为止我所知道的最好的一个。

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. String本身没有多大意义。 createWithThingNames , or something. createWithThingNames ,或者其他东西。

Some statically-typed languages do not have method overload at all (deliberately). 一些静态类型的语言根本没有方法过载(故意)。

Differents solutions : 不同的解决方案:

1) with tabs 1)带标签

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

2) with generics 2)具有泛型

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM