java generics (recursive generic

2020-03-03  本文已影响0人  巷及清晨

1、在调试es代码时,发现有这样一种泛型的用法:

public abstract class AbstractQueryBuilder<QB extends AbstractQueryBuilder<QB>>

如上所示,QB extends AbstractQueryBuilder<QB>,这里的泛型QB使用了extends是什么意思?

2、这是一种泛型递归的用法,

首先,定义StatusCode类(实现Comparable接口,调用compare()进行测试)

public class StatusCode<T extends StatusCode<T>> implements Comparable<T>

再定义SubStatusCode类

public class SubStatusCode extends StatusCode<SubStatusCode>

测试:

SubStatusCode subStatusCode = new SubStatusCode();

Object o = new Object();

subStatusCode.compareTo(o); //The method compareTo(SubStatusCode) in the type Comparable<SubStatusCode> is not applicable for the arguments (Object)

如上述报错信息提示,通过T extends StatusCode<T>,限定了T必须是StatusCode的子类,起到类型约束的作用。

上一篇下一篇

猜你喜欢

热点阅读