Created
December 2, 2015 20:30
-
-
Save erodozer/0a922ac15a6845859db3 to your computer and use it in GitHub Desktop.
String to Boolean
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ConversionUtility { | |
/** | |
* Set of appropriate types of Strings that we may convert booleans into or parse from | |
*/ | |
public static enum BooleanConversion { | |
YN("Y", "N"), YesNo("Yes", "No"), TrueFalse("True", "False"); | |
public final String True; | |
public final String False; | |
private BooleanConversion(String t, String f) { | |
this.True = t; | |
this.False = f; | |
} | |
} | |
/** | |
* Converts a boolean value into a string according to a supplied conversion specification | |
* @param value - boolean to be converted into a string | |
* @param to - conversion specification | |
* @return true or false String representations as identified by the conversion specification | |
*/ | |
public static String booleanToString(Boolean value, BooleanConversion to) { | |
if (value == null) { | |
return to.False; | |
} | |
return (value) ? to.True : to.False; | |
} | |
/** | |
* Attempts to convert a string into a boolean following the specification provided for conversion | |
* @param value - string to convert | |
* @param from - conversion specification to match against | |
* @returns a boolean value, or null if the string does not parse correctly into one of the boolean values | |
*/ | |
public static Boolean stringToBoolean(String value, BooleanConversion from) { | |
if (value == null) { | |
return null; | |
} | |
return (value.equals(from.True)) ? true : (value.equals(from.False)) ? false : null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment