我想制作一個具有兩個抽象方法的泛型介面,其中一個回傳并使用具有相同介面泛型型別的子型別。
我想要實作的目標是創造@FunctionalInterfaces擁有相同的父母,但組成自己的方式不同。
我的第一種方法如下,
public interface ParentFunction<T, C extends ParentFunction> {
void doSomething(T t);
C<T> compose(C<T> other);
}
@FunctionalInterface
public interface SonFunction<T> extends ParentFunction<T, SonFunction> {
@Override
default SonFunction<T> compose(SonFunction<T> other){
return null;
}
}
@FunctionalInterface
public interface SonFunction<T> extends ParentFunction<T, SonFunction> {
@Override
default DaughterFunction<T> compose(SonFunction<T> other){
return null;
}
}
但是在父方法中出現編譯錯誤,C<T>說“型別“C”沒有型別引數”,而在@Override子默認方法中出現另一個錯誤。
我可以在不擴展的情況下分離我的子介面,但我希望它們有一個只有客戶端代碼知道的超型別。
有什么很酷的技術可以用來實作它嗎?
uj5u.com熱心網友回復:
在 Java 中,您不能這樣做C<T>,但是,您可以要求 C 擴展ParentFunction<T,C>
同樣適用于您的SonFunctionand DaughterFunction。
嘗試這個:
public interface ParentFunction<T, C extends ParentFunction<T, C>> {
void doSomething(T t);
C compose(C other);
}
@FunctionalInterface
public interface SonFunction<T> extends ParentFunction<T, SonFunction<T>> {
@Override
default SonFunction<T> compose(SonFunction<T> other){
return null;
}
}
@FunctionalInterface
public interface DaughterFunction<T> extends ParentFunction<T, DaughterFunction<T>> {
@Override
default DaughterFunction<T> compose(DaughterFunction<T> other){
return null;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/435076.html
