如何理解这样的通用净值代码?

时间:2019-03-11 09:37:32

标签: java generics

我是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();
}

Constant的泛型定义是self的子类,这使我感觉像是循环引用。这样的代码的目的是什么?

1 个答案:

答案 0 :(得分:2)

该接口的设计者想要实际的实现工具Comparable,因此需要一段代码extends Comparable<T>。但不是比较任何对象,而是比较相同常量的其他实例。

因此,T在此情况下表示实现Constant的实际类型。

如果要实现它,则必须编写如下内容:

public class MyConstant implements Constant<MyConstant> {

    ...

    @Override
    public int compareTo(MyConstant myConstant) {
        return 0;
    }
}

T上的约束迫使实现提供方法compareTo(MyConstant myConstant)

此主题有a nice tutorial

相关问题