猿问

如何理解这种通用的netty代码?

我是Java的新手,现在最近学习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 的子类,这让我感觉像一个循环引用。这种代码的目的是什么?


温温酱
浏览 137回答 1
1回答

智慧大石

这个接口的设计师想要实际的实现实现,因此是一段代码。但不是比较任何对象,而是比较同一常量的其他实例。Comparableextends Comparable<T>因此,在此上下文中表示实现 的实际类型。TConstant如果你想实现它,你必须写这样的东西:public class MyConstant implements Constant<MyConstant> {&nbsp; &nbsp; ...&nbsp; &nbsp; @Override&nbsp; &nbsp; public int compareTo(MyConstant myConstant) {&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; }}上的约束强制实现提供方法。TcompareTo(MyConstant myConstant)
随时随地看视频慕课网APP

相关分类

Java
我要回答