如何查找集合类型?
我有两个变量
Collection<Service> services = new ArrayList<Service>();
Collection<Subscription> subscriptions = new ArrayList<Subscription>();
,我有以下方法,我想知道如何找到“?”的值在这个方法中,或者我如何知道服务是否已通过或订阅是否已通过?
myMethod(Collection<?> myCollection) {
if (myCollection is of type Service) {
// process service
}
else if (myCollection is of type Subscription) {
// process subscription
}
}
谢谢。
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 "?" 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能。 Java 具有基于擦除的泛型,这意味着类型参数在运行时不可用。
当然,如果您的集合不为空,您可以对第一个元素或其他元素执行
instanceof
。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.在泛型方法中使用 if-else 结构违背了泛型的目的。如果您需要知道在运行时传入的内容的类型,它确实不应该是通用的,您应该为每种类型编写一个单独的方法。
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.
Java 没有办法完全做到这一点。类型擦除会妨碍。如果你需要这样做,这也可能是一个设计问题。
但如果你必须这样做,有一种可怕的方法可以做到这一点:
更改变量以
注意 () 后面的 {}。您不是在创建一个 ArrayList,而是创建一个继承自 ArrayList 的匿名类。并且类型擦除在那里不适用。因此,您可以通过执行类似
该方法将返回实际类的操作来判断真实类型。它确实有效,这很恶心。这取决于你。
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
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
That method will return the actual class. It does work, it is disgusting. It is up to you.