本文介绍了有界的Java泛型没有编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法得到这个编译,我看不出原因。
最终,我想传递一个对象的集合,这些对象的类将TClass扩展到generate方法中,该方法需要一个类扩展TClass的对象集合
这应该起作用。



任何帮助将不胜感激。

  public interface Generator< IT extends ITClass,T extends TClass> {

IT生成(收集T类类集合)
}

生成器<?,?扩展TClass> generator = generatorClass.newInstance();

收藏

... generator.generate(TClassCollection);



我得到这个错误

 在类型
Generator& lt; capture#7-of,capture#8-of?的方法中生成(收集& lt; capture#8-of?extends TClass>扩展TClass>不适用于参数(Collection& lt; capture#9-of?extends TClass>)


解决方案

泛型声明中的通配符并不意味着任何类型;它意味着一些特定的未知类型。

因此,如果你有一个 Generator< ?,?扩展TClass> ,并不意味着你可以传递它的 generate()方法任何集合 TClass 的子类型。相反,这意味着你不能在类型安全中调用它的 generate()方法方式,因为你不知道它能够接受的元素的类型。


I am unable to get this to compile and I don't see the reason why.Ultimately I want to pass an Collection of objects who's class extends TClass into the generate method that takes a Collection of objects who's class extends TClass,This should work.

Any help would be appreciated.

public interface Generator<IT extends ITClass, T extends TClass> {

    IT generate(Collection<T> tClassCollection)
}

Generator<?, ? extends TClass> generator = generatorClass.newInstance();

Collection<? extends TClass> TClassCollection = ...

... generator.generate(TClassCollection);

I get this error

The method generate(Collection&lt;capture#8-of ? extends TClass>) in the type
Generator&lt;capture#7-of ?,capture#8-of ? extends TClass> is not applicable for the arguments (Collection&lt;capture#9-of ? extends TClass>)
解决方案

A wildcard in a generic declaration doesn't mean "any type"; it means "some particular unknown type."

So, if you have a Generator<?, ? extends TClass>, it doesn't mean you can pass its generate() method any Collection as long as it contains a subtype of TClass.

On the contrary, it means that you can't invoke its generate() method in a type-safe way, because you don't know the type of elements it is capable of accepting.

这篇关于有界的Java泛型没有编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 05:03