Ben*_*enj 4 java generics overriding derived-class type-erasure
我遇到了一个问题,我正试图实施"两级"演员.
下面是显示我想要做的简化代码:
public class Array2D<T>
{
private T[][] _array;
....
public T get( int x , int y )
....
public void set( T o , int x , int y )
}
Run Code Online (Sandbox Code Playgroud)
直到那里,没有问题.
我正在尝试扩展这个类,例如我可以在getter和setter中封装SoftReferences的使用:
public class Array2DSoftRefs<T> extends Array2D<SoftReference<T>>
{
public T get( int x , int y )
{
return super.get(x,y).get(); // get the array element, then the SoftReference contents
}
....
public void set( T o , int x , int y )
{
super.set( new SoftReference<T>(o) ,x,y); // generate the SoftReference on-the-fly
}
Run Code Online (Sandbox Code Playgroud)
}
事实上,我开始因为编译器/语法分析器跳过了泛型擦除,然后@Override注释无法帮助我(队长明显).
我无法弄清楚如何T从SoftReference<T>模板中返回一个类型.
我试图把两种仿制药T和U针对SoftReference<T>,但没有成功.
问题Array2DSoftRef.get是您不能覆盖方法并使其返回类型不太具体(例如SoftReference<T>- > T).
问题Array2DSoftRef.set是,如果方法具有不同的参数(例如,T而不是SoftReference<T>),则不能覆盖该方法,但如果在擦除后它具有相同的参数,则也不能重载它.
我建议你在这里使用组合而不是继承:
public class Array2DSoftRefs<T> {
private final Array2D<SoftReference<T>> inner = ...;
public T get( int x , int y ) {
return inner.get(x,y).get();
}
public void set( T o , int x , int y ) {
inner.set(new SoftReference<T>(o), x, y);
}
}
Run Code Online (Sandbox Code Playgroud)
否则,你将不得不重命名get,并set在Array2DSoftRefs避免名称冲突-但请记住父get和set仍然被人当众揭发这种方式.
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |