1

My case is different but as an example

public interface Comparable<T> 

would allow me to say:

public class MyType implements Comparable<OtherType>

but this is rarely what you want to achieve.

Is there a way to force me to say:

public class MyType implements Comparable<MyType>

The closest I got is:

public interface Comparable<T extends Comparable<T>>

This only works partially, as it won't allow OtherType if it's not comparable itself, but would allow:

public class MyType implements Comparable<Integer>

as it meets the conditions.

Mordechai
  • 15,437
  • 2
  • 41
  • 82
  • 5
    Can't be done in Java. At least not at compile time. – shmosel Feb 27 '17 at 20:25
  • 2
    Maybe if you say why do you need such a restriction enforced at compile time we can come up with different design. See http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – SergGr Feb 27 '17 at 20:37
  • @SergGr Simply to reduce a check at runtime. The default method of that interface does a whole annotation processing, and strictly requires them to be of same type (or at-least a sub-type). – Mordechai Feb 27 '17 at 20:40
  • And why that interface has to be generic at all? Does it have some input or output params of the generic type? Can't it use just `this.getClass()` in the code? – SergGr Feb 27 '17 at 23:55
  • @SergGr more precisely, I'm defining an interface `Copyable` with method `default void copyFrom(T other)` and scan field after field for the `@CopyField` annotation... Etc. – Mordechai Feb 28 '17 at 01:53
  • And reflectively sets all these fields in `this` equals to its corresponding field in `other`. – Mordechai Feb 28 '17 at 01:59
  • maybe related: http://stackoverflow.com/questions/2165613/java-generic-type – Ray Tayek Mar 01 '17 at 03:03

1 Answers1

3

This is not possible in Java.

Consider if it were possible to require that the type argument of Comparable be the same as the implementing class. Then if you had a class Foo implements Comparable<Foo>, and then also a class Bar extends Foo, Bar would also automatically implement Comparable<Foo> by the way that inheritance in Java works. But that would violate the constraint that the implementing class is the same as the type argument, as Bar does not implement Comparable<Bar> (and you can't even explicitly have Bar implement Comparable<Bar>, as a class cannot implement a generic type with two different type arguments).

newacct
  • 119,665
  • 29
  • 163
  • 224