2012-10-16 28 views
1

我有一些問題來編譯我的代碼。如何解決泛型遞歸邊界問題?

$ mvn clean compile 

通知我這種錯誤。

[58,30] type parameters of <D,K>D cannot be determined; no unique maximal instance exists for type variable D with upper bounds DS, 

也許這個問題是由recursive bounds of generic types造成的。對?

參考文獻: Generics compiles and runs in Eclipse, but doesn't compile in javac

我怎麼能解決這個問題嗎?

@SuppressWarnings("unchecked") 
public static <D extends DataStore<K, T>, K, T extends Persistent> D createDataStore(Class<T> persistent, Properties properties) throws IOException { 
    try { 
     return (D) (new HBaseStore<K, T>()); 
    } catch (Exception e) { 
     throw new RuntimeException("cannot initialize a datastore", e); 
    } 
} 

public static <DS extends DataStore<U, P>, U, P extends Persistent> DS createDataStore(Class<P> persistent) throws IOException { 
    return createDataStore(persistent, null); // ERROR 
} 

回答

1

這意味着類型D僅作爲通用參數存在。例如,可以從方法參數Class<T> persistent解析T

public static <D extends DataStore<K, T>, K, T extends Persistent> D createDataStore(Class<T> persistent, Class<D> dataStoreType, Properties properties) 
0

當類型的參數沒有提供足夠的信息讓編譯器推斷泛型類型參數,你可以明確地給出的參數類型:如果你改變了方法的簽名像就可以解決這個問題。對於非靜態方法,你會說this.<list of type parameters>methodName(...)。對於這樣的靜態方法,你可以將類名替換爲this

public static <DS extends DataStore<U, P>, U, P extends Persistent> DS createDataStore(Class<P> persistent) throws IOException { 
    return NameOfThisClass.<DS, U, P>createDataStore(persistent, null); // ERROR 
}