3

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?

2 Answers 2

2

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 );
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thanks, I want to try to do it in one method and do not want to ignore the warning. There has to be a way to specify the type of a generic class, I would think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.