Skip to content

Instantly share code, notes, and snippets.

@erodozer
Created December 2, 2015 20:30
Show Gist options
  • Save erodozer/0a922ac15a6845859db3 to your computer and use it in GitHub Desktop.
Save erodozer/0a922ac15a6845859db3 to your computer and use it in GitHub Desktop.
String to Boolean
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