I have a List<?> listin Java.
Is there a way to determine the type of the contents of that list at runtime when the list is empty?
I have a List<?> list in Java. Is there a way to determine the
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Unfortunately, you can’t figure out the type due to erasure — in fact, even if the list is not empty you still can not reliably determine what the what the list really is.
Let’s say right now your List<?> contains 2 elements: a Double and and Integer … it would be nontrivial to figure out that it might be a List<Number> … and even then, it may really be a List<Object> and someone could add a String later.
Furthermore, let’s say it’s really a List<List<String>>. The most you’ll figure out without attempting to recurse is that it’s a List<List<?>>.
There is a bright side . Depending on your situation, you may be able to use Type Tokens to work around erasure in a typesafe way. There’s a great post here: http://gafter.blogspot.com/2006/12/super-type-tokens.html