Java derived generic type erasures

I come with a problem, I'm trying to implement two-level casting.

The following is simplified code to show what I'm trying to do:

public class Array2D<T> { private T[][] _array; .... public T get( int x , int y ) .... public void set( T o , int x , int y ) } 

There are no problems before that.

I am trying to extend this class, for example, I could encapsulate the use of SoftReferences in getter and setter:

 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 } 

}

In fact, they launch me because the compiler / syntax analyzer skips overwriting generics, then the @Override annotation cannot help me (captain obviously).

I cannot figure out how to return type T from the SoftReference<T> template.

I tried to add two generics T and U for SoftReference<T> , but without success.

+4
source share
1 answer

The problem with Array2DSoftRef.get is that you cannot override the method and make its return type less specific (for example, SoftReference<T>T ).

The problem with Array2DSoftRef.set is that you cannot override the method if it has different parameters (for example, T instead of SoftReference<T> ), but you also cannot overload it if it has the same parameters after erasure .

I would recommend you use composition instead of inheritance here:

 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); } } 

Otherwise, you will have to rename your get and set to Array2DSoftRefs to avoid a name clash, but remember that the parent get and set will still be publicly presented this way.

+9
source

All Articles