Java generics to enforce return type of abstract method

前端 未结 5 1971
既然无缘
既然无缘 2020-12-17 18:59

I have the following situation :

abstract class X { abstract X someMethod (...) {...} }.

Now I want to constrain any implementation of X to

5条回答
  •  星月不相逢
    2020-12-17 19:33

    abstract class X> {
        protected X(Class implClazz) {
            if (!getClass().equals(implClazz)) {
                throw new IllegalArgumentException();
            }
        }
    
        abstract I someMethod();
    }
    

    Rationale: You can not refer to the dynamic type in type bounds, hence the indirect check in the constructor.

提交回复
热议问题