2017-08-18 32 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的第一个类型参数。