2017-10-05 95 views
-1
public class Demo { 
    public String work(String s) { 
     return s; 
    } 

    public <T> T Test(T t) { 
     // common work to do !! 
     // ..... 
     // spec work to do 
     T result = work(t); 
     return result; 
    } 
} 

測試()具有一些共同工作的第一做,然後相對於具體的工作,以不同類型的T. 的以上代碼導致編譯器錯誤,我怎樣才能做這個 ? 非常感謝!Java泛型參數不能應用於特定類型

+2

你不能做這樣的在Java中任何東西。在編譯時決定選擇哪種方法的重載,而不是運行時。 –

+0

我該如何實現? Test()需要處理不同的參數類型,並且需要先在該函數中完成一些常見工作,我只是想將通用部分提取到Test()中。 – TAW8750

+0

將公共部分拉出到一個單獨的方法,並有多個測試重載,調用該單獨的方法,然後執行專門的工作。 –

回答

-1

另一種方法是使用反射。請注意,反射是一個強大的工具,但它也是有代價的進行測量,看看這是否是一個可行的解決方案是你的具體情況(性能):

public class Demo { 
    private String work(String s) { 
    return s.toUpperCase(); 
    } 

    private Boolean work(Boolean b) { 
    return !b; 
    } 

    public <T> T test(T t) { 
    // common work to do !! 
    // ..... 

    // Now look-up "work" method for type T. Invoke if defined. 
    T result = null; 
    try { 
     Class<T> tType = (Class<T>) t.getClass(); 
     Method work = Demo.class.getDeclaredMethod("work", tType); 
     if (work.getReturnType() != tType) { 
     throw new NoSuchMethodException("No `work` method for type: " + tType); 
     } 

     result = (T) work.invoke(this, t); 
    } catch (NoSuchMethodException e) { 
     // NOOP - or whatever. 
    } catch (IllegalAccessException | InvocationTargetException e) { 
     // Method invocation failed. Handle properly. 
     e.printStackTrace(); 
    } 

    return result; 
    } 
} 
+0

謝謝,這可以做我想要的! – TAW8750

0

有很多事情可能導致你的代碼不能在這裏編譯;除了';'之外,你正在從無效方法中返回一些東西。請發佈您也面臨的編譯器錯誤,這會讓潛在的響應者更清楚。

+0

對不起,這是一個簡單的一塊來演示該問題 的主要錯誤是參數不匹配 它說: 工作()需要參數(如String),但通過一件T (generic type) – TAW8750

0

什麼你可以可能逃脫是創建T類型映射到(unary?)function。然後,在test方法中,您可以查找類型T。如果一個函數是registerede,適用於:

public class Demo { 
    private static final Map<Class<?>, UnaryOperator<?>> typeFuncs = new HashMap<>(); 
    static {{ 
    addTypeFunc(String.class, (String s) -> s); // Anonymous function. 
    addTypeFunc(Integer.class, Demo::workInteger); // Function reference. 
    }} 

    private static <T> void addTypeFunc(Class<T> type, UnaryOperator<T> func) { 
    typeFuncs.put(type, func); 
    } 

    private static Integer workInteger(Integer i) { 
    return i; 
    } 

    public <T> T test(T t) { 
    // common work to do !! 
    // ..... 

    T result = null; 
    UnaryOperator<T> operator = (UnaryOperator<T>) typeFuncs.get(t.getClass()); 
    if (operator != null) { 
     result = operator.apply(t); 
    } 

    return result; 
    } 
} 

請注意,test(UnaryOperator<T>)僅僅是安全的,因爲我們在typeFuncs地圖鍵和值類型之間的關係的總量控制。

+0

非常感謝,這個工程,但它帶來兩個限制: 1)需要手動調用addTypeFunc() 2)UnaryOperator可能不夠 不優雅 – TAW8750

+0

@ TAW8750是的,1)需要明確映射類型和適用功能之間。 2)什麼? – jensgram

+0

2) UnaryOperator operator =(UnaryOperator )typeFuncs.get(t.getClass()); 這裏的操作符可能很複雜,例如:很多參數 – TAW8750