简体   繁体   English

可比接口的一般化

[英]Generalization of Comparable interface

Identity Interface was implemented in the system years ago. 身份接口是在几年前在系统中实现的。 At this point, we got the necessity that each Identity should be Comparable. 在这一点上,我们有必要使每个身份都具有可比性。 One of the options is to add additional & Comparable type to Identity declaration: 选项之一是向Identity声明添加其他&Comparable类型:

interface Identity<K> {

}

class Handler<T extends Identity<?> & Comparable<T>> {

  Handler(T value) {
    Util.<T>handle(value);
  }
}

class Handler2<T extends Identity<?> & Comparable<T>> {

  Handler2(T value) {
    Util.<T>handle(value);
  }
}

interface Util {

  static <T extends Comparable<T>> void handle(T value) {
  }
}

One of the main disadvantages is that a huge amount of code should be enhanced with identical information (eg & Comparable ). 主要缺点之一是应使用相同的信息(例如&Comparable )增强大量代码。 Much elegant solution would be to extend Comparable interface with Identity one: 一个非常优雅的解决方案是使用身份标识1扩展Comparable接口:

interface Identity<K> extends Comparable<Identity<K>>{

}

But in this case Handler class will highlight a compilation error: 但是在这种情况下, Handler类将突出显示编译错误:

error: method handle in interface Util cannot be applied to given types; 错误:接口Util中的方法句柄无法应用于给定类型; required: T#1 found: T#2 reason: explicit type argument T#2 does not conform to declared bound(s) Comparable where T#1,T#2 are type-variables: T#1 extends Comparable declared in method handle(T#1) T#2 extends Identity declared in class Handler 必需:已找到T#1:T#2原因:显式类型参数T#2不符合声明的边界可比较,其中T#1,T#2是类型变量:T#1扩展了方法句柄中声明的Comparable (T#1)T#2扩展了在类Handler中声明的身份

What are the possible solutions in this situation? 在这种情况下有什么可能的解决方案?

After changing Identity to what you suggested Identity更改为您建议的

interface Identity<K> extends Comparable<Identity<K>>{

}

You have two options. 您有两个选择。 Either: 或者:

class Handler<T, U extends Identity<T>>
{
    Handler(U value) {
        Util.handle(value);
    }
}

Sample usage: 用法示例:

Handler<String, Identity<String>> stringHandler = new Handler<>(new FooIdentity());

or 要么

class Handler<T>
{
    Handler(Identity<T> value)
    {
        Util.handle(value);
    }
}

Sample usage: 用法示例:

final Handler<String> stringHandler = new Handler<>(new FooIdentity());

And Util can remain unchanged. Util可以保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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