Java泛型语法

stu*_*ent 12 java generics

我想了解以下是什么意思?

public class Bar<T extends Bar<T>> extends Foo<T> {
    //Some code
}
Run Code Online (Sandbox Code Playgroud)

做这样的事情有什么好处(例如用例?).

ass*_*ias 7

这是一个相当理论的例子,但在这种情况下你可能需要它:

public class Bar<T extends Bar<T>> extends Foo<T> {

    private final T value;

    public T getValue() { return value; }

    public void method(T param) {
        if (param.getValue().equals(someValue)) {
            doSomething();
        } else {
            doSomethingElse();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

param.getValue()如果T不是a Bar,你将无法打电话,这是因为T extends Bar<T>.

  • 请注意,`Bar`应该是抽象的,因为它永远不能直接使用.请参阅我的回答:http://stackoverflow.com/questions/7354740/is-there-a-way-to-refer-to-the-current-type-with-a-type-variable/7355094#7355094 (2认同)