具有其他类型的Collection getter的泛型类 [英] Generic classes with Collection getter of other types
问题描述
我有类似这样的东西:
public class GenericClass< T> {
T doSomething(){...}
集合< String> getCollection(){...}
}
现在我实例化该类的一个对象没有类型参数,因为我没有在这方面进行讨论,或者我不知道它。
GenericClass obj = new GenericClass ();
for(String str:obj.getCollection(){// does not work
...
}
问题是,编译器不会简单地抛弃有关类型参数的信息,而且还会抛出Collection(String)的类型,尽管这与参数无关。
我做错了什么,或者是Java的限制?如果是这样,为什么会有这个限制?
当你不知道 T时,你做错了什么。 $ b <
类型,你应该使用通配符: GenericClass<>
。当你实例化一个新的 GenericClass
,所以只需使用 Object
:
GenericClass<?> obj = new GenericClass< Object>();
出于向后兼容性的原因,故意在一个没有任何通用信息的类上所有( GenericClass
没有任何<>
)都会失去所有泛型类型的安全性,可以与预先通用的代码一起使用。
currenty I'm facing a problem with generic classes in Java.
I have something like this:
public class GenericClass<T> {
T doSomething() {...}
Collection<String> getCollection() {...}
}
Now I instantiate an object of that class without the type parameter, since I'm not intereseted in that or I don't know it.
GenericClass obj = new GenericClass();
for (String str : obj.getCollection() { // won't work
...
}
The problem is, that the compiler does not simply throw away the information about the type-parameter, but also about the type of the Collection (String), although that's independent from the parameter.
Am I doing something wrong, or is that a restriction of Java? If so, why is that a restriction?
You're doing something wrong.
When you don't know the T
type, you should just use a wildcard: GenericClass<?>
. You can't do this when you're instantiating a new GenericClass
, though, so just use Object
:
GenericClass<?> obj = new GenericClass<Object>();
For backwards-compatibility reasons, it is deliberate that a class without any generic information at all (GenericClass
without any <>
) loses all generic type safety so it can be used safely with pre-generic code.
这篇关于具有其他类型的Collection getter的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!