How can I know if Object is String type object?

后端 未结 8 1807
北荒
北荒 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 12:47

    From JDK 14+ which includes JEP 305 we can do Pattern Matching for instanceof

    Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type.

    Before Java 14

    if (obj instanceof String) {
        String str = (String) obj; // need to declare and cast again the object
        .. str.contains(..) ..
    }else{
         str = ....
    }
    

    Java 14 enhancements

    if (!(obj instanceof String str)) {
        .. str.contains(..) .. // no need to declare str object again with casting
    } else {
        .. str....
    }
    

    We can also combine the type check and other conditions together

    if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
    

    The use of pattern matching in instanceof should reduce the overall number of explicit casts in Java programs.

    PS: instanceOf will only match when the object is not null, then only it can be assigned to str.

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

    Guard your cast with instanceof

    String myString;
    if (object instanceof String) {
      myString = (String) object;
    }
    
    0 讨论(0)
  • 2020-12-13 12:59

    Use the instanceof syntax.

    Like so:

    Object foo = "";
    
    if( foo instanceof String ) {
      // do something String related to foo
    }
    
    0 讨论(0)
  • 2020-12-13 12:59

    Its possible you don't need to know depending on what you are doing with it.

    String myString = object.toString();
    

    or if object can be null

    String myString = String.valueOf(object);
    
    0 讨论(0)
  • 2020-12-13 13:01
     object instanceof Type
    

    is true if the object is a Type or a subclass of Type

     object.getClass().equals(Type.class) 
    

    is true only if the object is a Type

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

    Either use instanceof or method Class.isAssignableFrom(Class<?> cls).

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