Reputation: 11309
I have a method call that parses a string and the second argument to the parse method is the type that it will return. 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.
How do I do that?
Upvotes: 3
Views: 388
Reputation: 86509
You can't use List<Person>.class
because of type erasure. At run time, there is no List<Person>.class
object. There is just one 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 );
Upvotes: 2
Reputation: 290
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.
Upvotes: 1