Get a boolean value from a Map @param map Source map @param key The key @return The boolean value @throws IllegalArgumentException If value cannot be converted to boolean
(Map<String, Object> map, String key)
| 595 | * @throws IllegalArgumentException If value cannot be converted to boolean |
| 596 | */ |
| 597 | public static Boolean getBoolean(Map<String, Object> map, String key) throws IllegalArgumentException { |
| 598 | Object value = map == null || key == null ? null : map.get(key); |
| 599 | if (value == null) { |
| 600 | return null; |
| 601 | } |
| 602 | |
| 603 | if (value instanceof Boolean) { |
| 604 | return (Boolean) value; |
| 605 | } |
| 606 | |
| 607 | if (value instanceof String) { |
| 608 | String str = ((String) value).toLowerCase(); |
| 609 | if (str.equals("true") || str.equals("false")) { |
| 610 | return Boolean.parseBoolean(str); |
| 611 | } |
| 612 | throw new IllegalArgumentException("Cannot convert String value '" + value + "' to boolean"); |
| 613 | } |
| 614 | |
| 615 | if (value instanceof Number) { |
| 616 | int intValue = ((Number) value).intValue(); |
| 617 | if (intValue == 0 || intValue == 1) { |
| 618 | return intValue != 0; |
| 619 | } |
| 620 | throw new IllegalArgumentException("Cannot convert Number value '" + value + "' to boolean. Only 0 and 1 are supported."); |
| 621 | } |
| 622 | |
| 623 | throw new IllegalArgumentException("Cannot convert value of type " + value.getClass().getName() + " to boolean"); |
| 624 | } |
| 625 | |
| 626 | /** |
| 627 | * Get a boolean value from a Map |
no test coverage detected