(String) or .toString()?

后端 未结 9 1532
慢半拍i
慢半拍i 2020-12-12 16:56

I have a method with an Object o parameter.

In this method, I exactly know there is a String in \"o\" which is not null. There is no need t

相关标签:
9条回答
  • 2020-12-12 17:26

    If you know the Object o is a String, I'd say just cast it to a String and enforce it that way. Calling toString() on an object that you know for sure is a String might just add confusion.

    If Object o might be anything other than a String, you'll need to call toString().

    0 讨论(0)
  • 2020-12-12 17:32

    Given that the reference type is an Object and all Objects have a toString() just call object.toString(). String.toString() just returns this.

    • toString() is less code to type.
    • toString() is less bytecode.
    • casting is an expensive operation VS a polymorphic call.
    • the cast could fail.
    • Use String.valueOf( object ) which just calls object.toString() if its not null.
    0 讨论(0)
  • 2020-12-12 17:41

    I would use a cast. That validates your "knowledge" that it's a string. If for whatever reason you end up with a bug and someone passes in something other than a string, I think it would be better to throw an exception (which a cast will do) than continue to execute with flawed data.

    0 讨论(0)
提交回复
热议问题