Is there a way to refer to the current type with a

2018-12-31 08:13发布

Suppose I'm trying to write a function to return an instance of the current type. Is there a way to make T refer to the exact subtype (so T should refer to B in class B)?

class A {
    <T extends A> foo();
}

class B extends A {
    @Override
    T foo();
}

7条回答
爱死公子算了
2楼-- · 2018-12-31 08:56

You should be able to do this using the recursive generic definition style that Java uses for enums:

class A<T extends A<T>> {
    T foo();
}
class B extends A<B> {
    @Override
    B foo();
}
查看更多
登录 后发表回答