2017-08-18 36 views
1

所以,我有一段代碼是這樣如何通過Object對象在功能接口/λ呼叫

public static void printStuff(Object[] stuffs, Function<?, String> func) { 
    for(Object stuff : stuffs) { 
     String stringStuff = func.apply(stuff); 
     System.out.println(stringStuff); 
     // or whatever, what is done with that String is not relevant 
    } 
    // ... 

此方法是用不同類型的數組被調用,並且相應func值,對於例如:

printStuff(arrayOfClasses, (Class<?> c) -> c.getSimpleName()); 
printStuff(arrayOfStrings, (String s) -> '"' + s + '"'); 
printStuff(arrayOfObjects, o -> o.toString()); 

所以我肯定需要我東西Object[],因爲它是不同類型之間方法的調用的第一個公共超。

而且在編譯時,我得到:

MyClass.java:6: error: incompatible types: Object cannot be converted to CAP#1 
     String stringStuff = func.apply(stuff); 
             ^
    where CAP#1 is a fresh type-variable: 
    CAP#1 extends Object from capture of ? 

我的猜測是,的javac咆哮的我給予Function<?, String>調用,其類型,Object參數,不extendObject

所以我的問題是,如何將Object參數傳遞給Function<?, String>

我可以改變的接口類型,<Object, String>,但是它破壞我的其他電話(帶Class[]String[]等),它會失去相當多泛型整點暗示,不是嗎?

除非有某種方法可以將我的stuffs類型更改爲類似<? extends Object>[]或泛型類型,我敢肯定這是不可能的。

在此先感謝,夥計們。

編輯:

如果我改變我的方法到一個通用的一個,

public static <U> void printStuff(Object[] stuffs, Function<U, String> func) { 

我仍然得到一個編譯錯誤:

MyClass.java:6: error: method apply in interface Function<T,R> cannot be applied to given types; 
      String stringStuff = func.apply(stuff); 
            ^
    required: U 
    found: Object 
    reason: argument mismatch; Object cannot be converted to U 
+3

你不能'公共靜態 void printStuff(T [] stuffs,Function func){'?? –

+0

和[解釋](https://docs.oracle.com/javase/tutorial/java/generics/capture.html)。 – Maaaatt

+0

不,唉。請參閱我的編輯 – joH1

回答

4

一個解決方案是使用方法:

public static <T> void printStuff(T[] stuffs, Function<T, String> func) { 
    for(T stuff : stuffs) { 
     // .... 
+0

你釘了它。謝謝! – joH1

2

至於第一碼:

public static void printStuff(Object[] stuffs, Function<?, String> func) { 
    for(Object stuff : stuffs) { 
     String stringStuff = func.apply(stuff); 
     System.out.println(stringStuff); 
     // or whatever, what is done with that String is not relevant 
    } 
} 

您收到此錯誤

MyClass.java:6: error: incompatible types: Object cannot be converted to CAP#1 

你得到這個錯誤,因爲?可以是任何更具體的類,例如你也可以傳遞一個類型爲Function<String, String>的參數func。

你可以解決這個問題通過聲明像

public static void printStuff(Object[] stuffs, Function<Object, String> func) 

或通過一般方法簽名:

public static <U> void printStuff(U[] stuffs, Function<? super U, String> func) { 
    for(U stuff : stuffs) { 
     String stringStuff = func.apply(stuff); 
     System.out.println(stringStuff); 
     // or whatever, what is done with that String is not relevant 
    } 
} 

重要的是,該陣列的類型是等於(或子類的)Function的第一個類型參數。