Reputation: 4868
I have implemented a java method with the following signature:
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 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.
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.
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.
Upvotes: 0
Views: 883
Reputation: 73578
Not with List<String.class>
, no. You need to use a TypeToken to get that sort of generic information. You also need to change your code to work with Type
instead of Class
.
Upvotes: 4
Reputation: 369623
Type Parameters are erased, they don't exist at runtime. There is no such thing as List<String>
at runtime, there is only List
.
So, the correct way to express a reflective proxy for List<String>
is … you can't. You can only express a reflective proxy for List
, the same way you do for any other class: List.class
.
Upvotes: 5