Adam Adam - 16 days ago 5
Java Question

What is "the result to the type expected by the invoker" in Java?

I've been working with JSONPath recently. It's

function's parameters have the following description in the documentation:

Parameters:
json a json object
jsonPath the json path
filters filters to be applied to the filter place holders [?] in the path
**<T> expected return type**


My question is about the fourth parameter. It doesn't seem to be something I can pass in explicitly, since the read() method's signature is
(Object json, String jsonPath, Predicate... filters)
. On JSONPath's GitHub page, I'm told that:


"When using JsonPath in java its important to know what type you
expect in your result. JsonPath will automatically try to cast the
result to the type expected by the invoker."


What exactly is mean by "the result type expected by the invoker"? How do I control this? Can I pass it in as an explicit parameter?

Answer

T isn't the "fourth parameter", it's the generic type parameter. JsonPath appears to be doing something rather odd/clever with its type signatures, as it tries to guess what the desired return type is at runtime.

When using JsonPath in java its important to know what type you expect in your result. JsonPath will automatically try to cast the result to the type expected by the invoker.

The "invoker" in this context is you, the caller. The MappingProvider interface enables this transformation, but only certain types are configured. To your specific question of "Is there something special about arrays/arraylists" I would hazard a guess that JsonPath doesn't return ArrayList objects, just List objects (notice they use List in the examples on GitHub), so it's likely all you need to do is change your return type to List<String> realData. Try to specify the interface, rather than specific implementation, you expect.

That said, this automatic-type-guessing behavior is atypical (and not something I actually thought was possible in Java), so don't be surprised if it's confusing. You're essentially being asked to guess what types JsonPath can return to you.