I have two variables
Collection<Service> services = new ArrayList<Service>();
Collection<Subscription> subscriptions = new ArrayList<Subscription>();
and I have the following method, I was wondering how can I find the value of "?"开发者_C百科 in this method, or how can I find if services was passed or subscriptions was passed?
myMethod(Collection<?> myCollection) {
if (myCollection is of type Service) {
// process service
}
else if (myCollection is of type Subscription) {
// process subscription
}
}
Thanks.
You cannot. Java has erasure-based generics, which means that the type parameters are not available at runtime.
If your collection is not empty, you can do an instanceof
on the first element or something, of course.
Using that if-else construct in a generic method defeats the purpose of generics. If you need to know the type of what is being passed in at runtime, it really shouldn't be generic and you should write a separate method for each type.
You can't (except by using reflection), since the generic type parameter gets erased during compilation.
And I would recommend you rethink your design rather than trying to solve it with generics. Passing arbitrary types of collections into the same method is a recipe for problems in the long run.
There is no Java way of doing exactly that. Type erasure gets in the way. And if you need to do so, it is also probably a design issue. But if you must, there is horrible way to do almost that:
Change your variables to
Collection<Service> services = new ArrayList<Service>(){};
Collection<Subscription> subscriptions = new ArrayList<Subscription>(){};
Note the {} after the (). You are not creating an ArrayList, but a anonymous class that inherits from ArrayList. And type erasure does not apply there. So you can tell the real type by doing something like
private static Class<?> detectType(Collection<?> col) {
return (Class<?>) ((ParameterizedType) col.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
That method will return the actual class. It does work, it is disgusting. It is up to you.
精彩评论