简体   繁体   中英

How to restrict generic type of interface to accept only implementor class

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM