我是Java的新手,現(xiàn)在最近學(xué)習(xí)netty。一些通用的類代碼讓我感到困惑。像這樣:package io.netty.util;/** * A singleton which is safe to compare via the {@code ==} operator. Created and managed by {@link ConstantPool}. */public interface Constant<T extends Constant<T>> extends Comparable<T> { /** * Returns the unique number assigned to this {@link Constant}. */ int id(); /** * Returns the name of this {@link Constant}. */ String name();}常量的通用定義是 self 的子類,這讓我感覺(jué)像一個(gè)循環(huán)引用。這種代碼的目的是什么?
1 回答

智慧大石
TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
這個(gè)接口的設(shè)計(jì)師想要實(shí)際的實(shí)現(xiàn)實(shí)現(xiàn),因此是一段代碼。但不是比較任何對(duì)象,而是比較同一常量的其他實(shí)例。Comparableextends Comparable<T>
因此,在此上下文中表示實(shí)現(xiàn) 的實(shí)際類型。TConstant
如果你想實(shí)現(xiàn)它,你必須寫這樣的東西:
public class MyConstant implements Constant<MyConstant> {
...
@Override
public int compareTo(MyConstant myConstant) {
return 0;
}
}
上的約束強(qiáng)制實(shí)現(xiàn)提供方法。TcompareTo(MyConstant myConstant)
添加回答
舉報(bào)
0/150
提交
取消