Java Object return type vs. Generic Methods

后端 未结 4 713
甜味超标
甜味超标 2021-02-18 16:28

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 :

4条回答
  •  礼貌的吻别
    2021-02-18 17:00

    The main reason that I would stay away from

    JsonPath.read(currentRule, "$.logged")
    

    is that it is internally performing an unchecked cast, and hiding this fact. For instance, you could invoke this method at the same place:

    JsonPath.read(currentRule, "$.logged")
    

    and there is no way that you'd know there might be a problem there until it actually happens at runtime - it still compiles, and you don't even get a warning.

    There is no getting away from the unchecked cast - I'd just rather have it right there in front of me in the code, so I know there is a potential danger; this allows me to take reasonable steps to mitigate the issue.

    @SuppressWarnings("unchecked")  // I know something might go wrong here!
    boolean value = (boolean) JsonPath.read(currentRule, "$.logged")
    

提交回复
热议问题