Coerces an object to an Enum value of the specified type. If the object is null or an empty string, null is returned. If the object is already an instance of the target enum type, it is returned directly. Otherwise, the object must be a String matching one of the enum constant names. @param ctx
(final ELContext ctx, final Object obj,
@SuppressWarnings("rawtypes") Class type)
| 194 | * @throws ELException if the object cannot be coerced to the target enum type |
| 195 | */ |
| 196 | @SuppressWarnings("unchecked") |
| 197 | public static Enum<?> coerceToEnum(final ELContext ctx, final Object obj, |
| 198 | @SuppressWarnings("rawtypes") Class type) { |
| 199 | |
| 200 | if (ctx != null) { |
| 201 | boolean originalIsPropertyResolved = ctx.isPropertyResolved(); |
| 202 | try { |
| 203 | Object result = ctx.getELResolver().convertToType(ctx, obj, type); |
| 204 | if (ctx.isPropertyResolved()) { |
| 205 | return (Enum<?>) result; |
| 206 | } |
| 207 | } finally { |
| 208 | ctx.setPropertyResolved(originalIsPropertyResolved); |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | if (obj == null || "".equals(obj)) { |
| 213 | return null; |
| 214 | } |
| 215 | if (type.isAssignableFrom(obj.getClass())) { |
| 216 | return (Enum<?>) obj; |
| 217 | } |
| 218 | |
| 219 | if (!(obj instanceof String)) { |
| 220 | throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); |
| 221 | } |
| 222 | |
| 223 | Enum<?> result; |
| 224 | try { |
| 225 | result = Enum.valueOf(type, (String) obj); |
| 226 | } catch (IllegalArgumentException iae) { |
| 227 | throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), type)); |
| 228 | } |
| 229 | return result; |
| 230 | } |
| 231 | |
| 232 | /** |
| 233 | * Convert an object to Boolean. Null and empty string are false. |