I saw several questions about generic return type, but none answers my question.
If there is no bound for any of the arguments, such as the following method in JayWay :
Having a type-parameter that has never been set (when calling JsonPath.read(currentRule, "$.logged")
), actually makes the compiler completely ignore all the generic information within the method and replace all the type-parameter with:
Object
, if the type-parameter doesn't have an upper-bound. (like in your case)U
, if the type-parameter is bounded like
. For example, if you have a
as a type-parameter and ignore it by calling JsonPath.read(...)
, then the compiler will replace the type-parameter with Number
.In the case with the cast ((boolean) JsonPath.read(...)
), the type-parameter is replaced with Object
. Then, this type is unsafely transformated to boolean
, by first returning a Boolean
(probably), and then auto-unboxing this wrapper to boolean
. This is not safe, at all. Actually, every cast is not safe - pretty much you tell the compiler: "I know what this type will be at Runtime, so please believe me, and let me cast it to something else that's compatible with it.". Your humble servant, the compiler, allows that, but that's not safe, if you're wrong. :)
There's another thing with your method, also. The type-parameter is never used within the method body or parameters - this makes it pretty redundant. Since by doing a cast to boolean
you insist that you know the return type of new JsonReader().parse(json).read(jsonPath, filters);
, then you should just make the return type boolean
(or Boolean
):
public static Boolean read(String json, String jsonPath, Filter... filters) {
return new JsonReader().parse(json).read(jsonPath, filters);
}