[英]How do you manually pass generic parameter to a method
I have the method: 我有方法:
public static <T> Stream<T> stream(JSONArray array) {
return IntStream.range(0, array.length()).mapToObj(i -> {
try {
return (T) array.get(i);
} catch (JSONException e) {
return null;
}
});
}
When I call it like this: stream(array).map((JSONObject object) -> { /* ... */ })
, I get the error 当我这样称呼它: stream(array).map((JSONObject object) -> { /* ... */ })
,我得到了错误
Cannot infer functional interface type 无法推断功能接口类型
And, stream<JSONObject>(array).map(object -> { /* ... */ })
doesn't work. 而且, stream<JSONObject>(array).map(object -> { /* ... */ })
不起作用。
stream(array).map(object -> { /* ... */ })
works, but object
is simply an Object
stream(array).map(object -> { /* ... */ })
可以,但是object
只是一个Object
And,
stream<JSONObject>(array).map(object -> { /* ... */ })
doesn't work. 而且,stream<JSONObject>(array).map(object -> { /* ... */ })
不起作用。
That's because you've put the type witness in the wrong place. 那是因为您将类型见证人放置在错误的位置。 Try: 尝试:
TheContainingClass.<JSONObject>stream(array).map(object -> { /* ... */ })
But your code is not type safe: the cast to T
is unchecked. 但是您的代码不是安全类型:到T
的强制转换未选中。 You should simply return a Stream<JSONObject>
, and let the caller handle the casting to other types. 您应该简单地返回Stream<JSONObject>
,并让调用方将类型转换为其他类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.