简体   繁体   English

如何在Java中定义类型的通用列表?

[英]How to define a generic List of types in java?

I have implemented a java method with the following signature: 我已经实现了具有以下签名的java方法:

public <T> T getItemValue(String itemName, Class<T> itemType)  {
...
}

This allows a client to call the method in the following way to get for example a value of the type String or Integer: 这允许客户端以以下方式调用该方法,以获取例如String或Integer类型的值:

String s = itemCol.getItemValue("_name", String.class);
int i = itemCol.getItemValue("_count", Integer.class);

This kind of method signature is also used by the Config interface of the new microprofile Config 1.3 API. 新的微配置文件Config 1.3 API的Config接口也使用这种方法签名。

My question is how - or if - I can call the method with a Type of List of Types like List<String> to get for example a List of String objects. 我的问题是如何(或是否)可以使用类型为List<String>的类型的List来调用该方法,以获取例如String对象的List。 I was not able to formulate the client call. 我无法提出客户电话。 I tried something like this: 我尝试过这样的事情:

List<String> list = itemCol.getItemValue("_count", List<String.class>);

but this seems not to be the correct syntax. 但这似乎不是正确的语法。

EDITED: 编辑:

As a result of the responses below I decided to add a separate method to get a List of a specific type. 由于以下响应,我决定添加一个单独的方法来获取特定类型的列表。

public <T> List<T> getItemValueList(String itemName, Class<T> itemType) {
        ...
}

With this additional method signature a client can decide weather to get a single value or a list of a specific type. 使用此附加方法签名,客户可以决定天气以获取单个值或特定类型的列表。

Type Parameters are erased, they don't exist at runtime. 类型参数被删除,它们在运行时不存在。 There is no such thing as List<String> at runtime, there is only List . 在运行时没有List<String>这样的东西,只有List

So, the correct way to express a reflective proxy for List<String> is … you can't. 因此,表达List<String>的反射代理的正确方法是…您不能。 You can only express a reflective proxy for List , the same way you do for any other class: List.class . 您只能为List表示反射型代理,就像对其他任何类List.class

Not with List<String.class> , no. 不与List<String.class> You need to use a TypeToken to get that sort of generic information. 您需要使用TypeToken来获得这种通用信息。 You also need to change your code to work with Type instead of Class . 您还需要更改代码以使用Type而不是Class

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

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