所以,我有一段代碼是這樣如何通過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
參數,不extend
Object
。
所以我的問題是,如何將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
你不能'公共靜態 void printStuff(T [] stuffs,Function func){'?? –
和[解釋](https://docs.oracle.com/javase/tutorial/java/generics/capture.html)。 – Maaaatt
不,唉。請參閱我的編輯 – joH1