2016-11-21 108 views
-2

我想製作一個我可以做的界面,例如正確的方法來做一個通用的接口方法?

public interface Getter { 
    T get(String location); 
} 

public class IntegerGetter { 
    Integer get(String location) { 
    Object x = foo(location); 
    if (!(x instanceOf Integer)) { throw Exception } 
    return (Integer) x; 
    } 
} 

什麼是安排仿製藥的正確方法,使這項工作?一種選擇似乎是使T成爲接口本身的類型參數,例如, Getter<T>,IntegerGetter<Integer>,但由於該參數僅用於一種方法,因此它更適合作爲方法參數。然而,我被告知只有類型參數是該方法的返回類型是危險的,例如, <T> T get

+1

什麼是'foo'在這裏? – flakes

+2

「,但由於參數僅用於一種方法,因此它更適合作爲方法參數。」不,它沒有任何意義。使用'Getter '和'IntegerGetter implements Getter '。 – bradimus

+0

@bradimus我提供的例子很少,但實際上我正在構建一些其他一些與類型無關的方法。在這種情況下,95%的用戶不會使用該方法,但他們仍然需要提供泛型類型參數。應該做得更清楚。你是否仍然說它沒有更多意義? –

回答

1

我已經被告知僅僅是類型參數是該方法的返回類型是危險的,例如, <T> T get

它沒有比你已經有的更危險。

簡化您的IntegerGetter一點:

class IntegerGetter { 
    Integer get(String location) { 
    return (Integer) foo(location); 
    } 
} 

可以定義一個等價類爲String S:

class StringGetter { 
    String get(String location) { 
    return (String) foo(location); 
    } 
} 

假設foo(String)在這兩個類相同的方法,它返回一個結果僅基於location,並且它不返回null,以下至少一行將失敗:

Integer i = new IntegerGetter().get("hello"); 
String s = new StringGetter().get("hello"); 

因爲foo("hello")不能同時爲StringInteger

所以,你可能也只是有單一的實現:

class SimplerGetter { 
    <T> T get(String location) { 
    return (T) foo(location); 
    } 
} 

將在完全相同的情況下,與單獨的類會失敗。

Integer i = new SimplerGetter().get("hello"); 
String s = new SimplerGetter().get("hello"); 
+0

如果您沒有在調用時指定類型,則會有所不同。 'Object o = new SimplerGetter()。get(「hello」);'。 – shmosel

1

你基本上實現的接口類似於Supplier。你可以把它當作參考。該界面需要輸入參數T,否則get方法可以用在調用上下文中,它可以返回任何類型的對象。