gpt4 book ai didi

java - 如何在功能接口(interface)/lambda 调用中传递 Object 对象

转载 作者:行者123 更新时间:2023-11-29 06:51:49 24 4
gpt4 key购买 nike

所以,我有一段代码是这样的

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[] ,因为它是方法调用中不同类型的第一个公共(public)父类(super class)。

在编译时,我得到:

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> 的参数?

我可以将接口(interface)类型更改为 <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

最佳答案

一种解决方案是使用:

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

关于java - 如何在功能接口(interface)/lambda 调用中传递 Object 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45761022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com