How can I know if Object is String type object?

后端 未结 8 1808
北荒
北荒 2020-12-13 12:43

I have to know if Object is String or any other class type, how can I do it? Currently I do it like below, but its not very good coding.

try {
          


        
相关标签:
8条回答
  • 2020-12-13 13:06

    javamonkey79 is right. But don't forget what you might want to do (e.g. try something else or notify someone) if object is not an instance of String.

    String myString;
    if (object instanceof String) {
      myString = (String) object;
    } else {
      // do something else     
    }
    

    BTW: If you use ClassCastException instead of Exception in your code above, you can be sure that you will catch the exception caused by casting object to String. And not any other exceptions caused by other code (e.g. NullPointerExceptions).

    0 讨论(0)
  • 2020-12-13 13:08

    Could you not use typeof(object) to compare against

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