简体   繁体   English

带类型的Java通用列表类

[英]Java Generic List Class with Type

I have a method call that parses a string and the second argument to the parse method is the type that it will return. 我有一个解析字符串的方法调用,而parse方法的第二个参数是它将返回的类型。 To parse a Person, we use: 要解析一个人,我们使用:

Person p = myParser.parse("name=Mike", Person.class);

This works great, and this works too for lists: 这很好用,这也适用于列表:

List<Person> lop = myParser.parse(somestring, List.class);

However, that gives me a compiler warning because what I really want is List<Person>.class , but I can't figure out the syntax. 但是,这给了我一个编译器警告,因为我真正想要的是List<Person>.class ,但我无法弄清楚语法。

How do I do that? 我怎么做?

You can't use List<Person>.class because of type erasure . 由于类型擦除,您不能使用List<Person>.class At run time, there is no List<Person>.class object. 在运行时,没有List<Person>.class对象。 There is just one List.class . 只有一个List.class (Or at most one per class loader.) (或者每个类加载器最多一个。)

What you could do instead is provide a sibling method that allows the caller to specify both the container type and its type parameters. 你可以做的是提供一个兄弟方法,允许调用者指定容器类型和它的类型参数。 For example: 例如:

List<Person> lop = myParser.parseList( somestring, Person.class );

Or, if you wanted to do a map: 或者,如果你想做一张地图:

Map<Person,Integer> map = myParser.parseMap( somestring, Person.class, Integer.class );

You can hack this a number of ways but the best is likely to be to add a method 您可以通过多种方式破解此方法,但最好的方法是添加方法

List<Person> lop = myParser.parseList(somestring, Person.class);

Your method will be able to "know" the type of the elements of the list. 您的方法将能够“知道”列表元素的类型。

Another way you can do this involve ignoring the warning, however this may be just hiding the problem. 另一种可以做到这一点的方法是忽略警告,但这可能只是隐藏了问题。

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

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