简体   繁体   中英

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

Cannot infer functional interface type

And, stream<JSONObject>(array).map(object -> { /* ... */ }) doesn't work.

stream(array).map(object -> { /* ... */ }) works, but object is simply an Object

And, stream<JSONObject>(array).map(object -> { /* ... */ }) doesn't work.

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. You should simply return a Stream<JSONObject> , and let the caller handle the casting to other types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM