How to convert String object to Boolean Object?

前端 未结 14 651
我寻月下人不归
我寻月下人不归 2020-11-28 01:28

How to convert String object to Boolean object?

相关标签:
14条回答
  • 2020-11-28 02:03

    you can directly set boolean value equivalent to any string by System class and access it anywhere..

    System.setProperty("n","false");
    System.setProperty("y","true");
    
    System.setProperty("yes","true");     
    System.setProperty("no","false");
    
    System.out.println(Boolean.getBoolean("n"));   //false
    System.out.println(Boolean.getBoolean("y"));   //true   
     System.out.println(Boolean.getBoolean("no"));  //false
    System.out.println(Boolean.getBoolean("yes"));  //true
    
    0 讨论(0)
  • 2020-11-28 02:05

    We created soyuz-to library to simplify this problem (convert X to Y). It's just a set of SO answers for similar questions. This might be strange to use the library for such a simple problem, but it really helps in a lot of similar cases.

    import io.thedocs.soyuz.to;
    
    Boolean aBoolean = to.Boolean("true");
    

    Please check it - it's very simple and has a lot of other useful features

    0 讨论(0)
  • 2020-11-28 02:07

    Try (depending on what result type you want):

    Boolean boolean1 = Boolean.valueOf("true");
    boolean boolean2 = Boolean.parseBoolean("true");
    

    Advantage:

    • Boolean: this does not create new instances of Boolean, so performance is better (and less garbage-collection). It reuses the two instances of either Boolean.TRUE or Boolean.FALSE.
    • boolean: no instance is needed, you use the primitive type.

    The official documentation is in the Javadoc.


    UPDATED:

    Autoboxing could also be used, but it has a performance cost.
    I suggest to use it only when you would have to cast yourself, not when the cast is avoidable.

    0 讨论(0)
  • 2020-11-28 02:07
    boolean b = string.equalsIgnoreCase("true");
    
    0 讨论(0)
  • 2020-11-28 02:13

    You have to be carefull when using Boolean.valueOf(string) or Boolean.parseBoolean(string). The reason for this is that the methods will always return false if the String is not equal to "true" (the case is ignored).

    For example:

    Boolean.valueOf("YES") -> false
    

    Because of that behaviour I would recommend to add some mechanism to ensure that the string which should be translated to a Boolean follows a specified format.

    For instance:

    if (string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false")) {
        Boolean.valueOf(string)
        // do something   
    } else {
        // throw some exception
    }
    
    0 讨论(0)
  • 2020-11-28 02:15

    Why not use a regular expression ?

    public static boolean toBoolean( String target )
    {
        if( target == null ) return false;
        return target.matches( "(?i:^(1|true|yes|oui|vrai|y)$)" );
    }
    
    0 讨论(0)
提交回复
热议问题