[英]java generic related to type inference
我是Java新手,並且有一些類似下面的代碼。
public interface TestJava<T extends MyClass, U> {
public U func(T t);
}
的問題是,U是完全依賴於T,使得如果T被確定,U也被確定(聲明U是不必要!)。 例如,如果T為String ,則U必須為Integer且不能為別人。 在C ++中 ,如果T是用戶定義的類,則可以使用關鍵字typedef輕松刪除U,如下所示。
class UserDefinedClass {
public:
typedef int ReturnType;
};
template<class T> class TestCpp {
T::ReturnType func(T t);
};
但是,據我所知,java沒有這樣的關鍵字,所以我不知道該如何實現。 請注意,Java代碼中的T是用戶定義的對象,而不是String , Integer或其他。 不要與示例混淆:)
您可以做的一件事是,通過擴展接口隱藏視線,然后再調用擴展接口。 這里的要點是,如果您確定第二種類型將始終保持相同(例如Integer *),則不必傳遞第二種類型。
public class MyClass{
boolean truth;
}
public interface Lame{
}
public interface TestJava<T extends MyClass, U> {
public U func(T t);
}
public interface TestJavaMore<T extends MyClass> extends Lame{
public void funky();
}
public interface TestJavaEvenMore<T extends MyClass> extends TestJava<T, Integer> {
}
我想建議的另一種解決方案是,如果T和U的類型組合不止一種,請使用工廠創建具有所需類型的具體實例。 這是您可以研究的常見模式,但在這種情況下,它類似於:
public class TestJavaImpl<T extends MyClass, U> implements TestJava{
@Override
public Object func(MyClass t) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
public TestJava TestJavaFactory(){
TestJava testJava = null;
if (true == true){
testJava = new TestJavaImpl<MyClass, Integer>();
} else {
testJava = new TestJavaImpl<MyClass, Float>();
}
return testJava;
}
*提示:請記住也要使用Java和模板,並且必須使用“ I” nteger而不是“ i” nteger
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.