unh*_*ler 6 java generics restriction type-erasure
我正在开发一个具有广泛的泛型继承和依赖树的项目.转到编辑以查看更好的示例.基础知识看起来像这样:
class A {
...
}
class B {
...
}
class C extends B {
...
}
class D<T extends B> extends A {
...
}
class StringMap<T extends A> {
HashMap<String, T> _elements;
...
}
Run Code Online (Sandbox Code Playgroud)
所以现在我要编写一个包含特定StringMap类型的类.
class X {
StringMap<D<C>> _thing = new StringMap<D<C>>;
...
}
Run Code Online (Sandbox Code Playgroud)
到目前为止这一切都很好.D<C>实际上是一个非常长的名称,并且特定组合将在代码的其他部分中非常频繁地出现,因此我决定使用特定组合的类,以便更清楚并且具有更短的名称.
class DC extends D<C> {
}
//and go to update X
class X {
StringMap<D<C>> _thing = new StringMap<D<C>>(); //still works fine
StringMap<DC> _thing = new StringMap<DC>(); //error
...
}
Run Code Online (Sandbox Code Playgroud)
Eclipse给出了错误
绑定不匹配:该类型
DC不是该类型的有界参数<T extends A>的有效替代StringMap<T>
所以问题是,为什么这不仅仅起作用?DC除了扩展D<C>和回应构造函数之外什么都不做.当它只是一个孩子类的东西时,为什么StringMap看到DC它不同?
编辑:
好的,重新设计的例子更接近我实际做的事情.我测试了它确实产生了错误.我在这里做的是使用泛型类型来确保clone()为继承树中实现它的人返回正确的类.然后在子类中,我B<T extends B<T>>用来确保子B类在B的子类中作为泛型类型传递T.
public abstract class Undoable<T> implements Comparable<T> {
public abstract T clone();
public abstract void updateFields(T modified);
}
abstract public class A<T extends A<T, U>, U extends Comparable<U>>
extends Undoable<T> {
abstract U getKey();
@Override
public int compareTo(T element)
{
return getKey().compareTo(element.getKey());
}
}
public class B<T extends B<T>> extends A<T, String> {
@Override
public T clone()
{
// TODO Auto-generated method stub
return null;
}
@Override
public void updateFields(T modified)
{
// TODO Auto-generated method stub
}
@Override
String getKey()
{
// TODO Auto-generated method stub
return null;
}
}
public class C extends B<C> {
}
public class D<T extends B<T>> extends A<D<T>, String> {
@Override
String getKey()
{
// TODO Auto-generated method stub
return null;
}
@Override
public D<T> clone()
{
// TODO Auto-generated method stub
return null;
}
@Override
public void updateFields(D<T> modified)
{
// TODO Auto-generated method stub
}
}
public class DC extends D<C> {
}
public class StringMap<T extends Undoable<T>> {
HashMap<String, T> _elements;
}
public class Main {
public static void main(String[] args)
{
StringMap<D<C>> _thing = new StringMap<D<C>>(); //works
StringMap<DC> _thing1 = new StringMap<DC>(); //error
//Bound mismatch: The type DC is not a valid substitute for
//the bounded parameter <T extends Undoable<T>> of the type StringMap<T>
}
}
Run Code Online (Sandbox Code Playgroud)
你必须做错其他的事情,因为以下工作正常:
import java.util.HashMap;
public class Q {
class A {
}
class B {
}
class C extends B {
}
class D<T extends B> extends A {
}
class StringMap<T extends A> {
HashMap<String, T> _elements;
}
class DC extends D<C> {
}
//and go to update X
class X {
StringMap<D<C>> thing1 = new StringMap<D<C>>(); // still works fine
StringMap<DC> thing2 = new StringMap<DC>(); // NO error!!!
}
}
Run Code Online (Sandbox Code Playgroud)
试着发布这样一个类来重现你的错误.