I have a generic function that returns a List<?>. If it works correctly, it will return a List<LightSensor>, but I cannot directly convert the result of the function to a variable of type List<LightSensor>. How can I check if the class in the List is a LightSensor correctly? (e.g. check if List<?> = List<LightSensor>)
Also, What is the best way to cast it correctly once I've checked?
BTW the class LightSensor extends Object and a version of Serializable
-
2Perhaps you should show us your generic function.Josh M– Josh M2013-09-19 00:46:27 +00:00Commented Sep 19, 2013 at 0:46
-
1Also, in Java, we call them "methods", not "functions".James Dunn– James Dunn2013-09-19 00:53:41 +00:00Commented Sep 19, 2013 at 0:53
-
It's nothing special, why do you need to see it? It just returns a List<?>. If you really want to see it, go here: jd.bukkit.org/rb/doxygen/df/d9a/…Pocketkid2– Pocketkid22013-09-19 00:55:00 +00:00Commented Sep 19, 2013 at 0:55
-
1@Pocketkid2 - read the "help". Inlined code should be enclosed in backticks.Stephen C– Stephen C2013-09-19 01:02:17 +00:00Commented Sep 19, 2013 at 1:02
-
1@TJamesBoone - there's a better way!Stephen C– Stephen C2013-09-19 01:03:21 +00:00Commented Sep 19, 2013 at 1:03
2 Answers
How can I check if the class in the List is a LightSensor correctly? (e.g. check if
List<?> = List<LightSensor>)
AFAIK, the only way to do this is to iterate the list and use instanceof LightSensor or getClass() == LightSensor.class on each element.
Also, What is the best way to cast it correctly once I've checked?
Just do a typecast, and suppress the "unchecked conversion" warning.
2 Comments
Object for iterating through the List<?>?List<?> is.Well the idiom to return a generic collection from a method is something like:
public <T> List<T> getTheList(Class<T> cls){
// you might need the cls in here to create the list.
...
}
Obviously the way you use the Class<T> to generate the list is application specific. Most of the times this makes sense in the context of some class hierarchy, in which case T extends some base class or interface:
public <T extends MyBaseClassOrInterface> List<T> getTheList(Class<T> cls){
...
}
Again, the way you create the list is completely application dependent. If you try to keep your whole application strongly typed you might be able to avoid doing some kind of black magic to figure out the type parameter of List<?>. It's a strong code smell if you end up with code like that (unless obviously you are dealing with some legacy code). Besides, if the list is empty you are absolutely hopeless.