How to avoid unverified throws in the Java Generics advanced interface?

Why is unsafe listing (T)necessary in this common interface? If it is Tcomparable to itself, that is, it implements ExtendedComparable<super of T>, which also means ExtendedComparable<T>, then why does type deletion require that ExtendedComparable<T>it be added to T?

/* @param <T> T must be comparable to itself or any of its superclass
 * (comparables are consumers, thus acc. to the PECS principle 
 * = producer-extends,consumer-super we use the bounded wildcard type "super")
 */   
public interface ExtendedComparable<T extends ExtendedComparable<? super T>> {
    Comparator<? super T> getComparator();
    default boolean greaterThen(T toCompare) {
        return getComparator().compare((T) this, toCompare) > 0;
    }
}
+6
source share
2 answers

Since there is no guarantee that it thisis actually an instance of a class Tor even extends it.

For example, consider the following:

public class T0 implements ExtendComparable<T0> {...}
public class T1 implements ExtendComparable<T0> {...}

T0 , : T0 extends ExtendComparable<T0> T0 T0. this T0, ; (T)this ( , (T0)this) .

T1 , T0 no T1, T T0. this T1, T1 T0. , ExtendedCompatible<T0>, . , Integer Double extend Number, (Integer) new Double(0.0) . (T) (T0).

, T , , , . , - Java-, , , , " " Java- .

, , ExtendedCompatible , .

T, , this :

public abstract class ExtendedCompatible<T extends ExtendedCompatible<? super T>> {
  private final T thiz;

  protected ExtendedCompatible(final T thiz) {
     if (this != thiz) throw new IllegalArgumentException("you must pass yourself");
     this.thiz = thiz;
  }
  ...

  public class MyExtendedCompatible extends ExtendedCompatible<MyExtendedCompatible> {
     public MyExtendedCompatible() {
           super(this);
     }
  }

, , - / this .

T (this):

// Parent abstract class:
   protected abstract T getThiz();
// Child class... for each class:
   protected MyChildClass getThiz() { return this; }
+5

. . , . , Java T , .

0

All Articles