Coerces an object to the specified target type. Supports coercion to String, Number, Character, Boolean, Enum, Instant, Date, arrays, and functional interfaces. Uses the ELResolver's convertToType method first if a context is provided. @param ctx the EL context @param obj the object to coerce @
(final ELContext ctx, final Object obj, final Class<T> type)
| 539 | * @throws ELException if the object cannot be coerced to the target type |
| 540 | */ |
| 541 | public static <T> T coerceToType(final ELContext ctx, final Object obj, final Class<T> type) throws ELException { |
| 542 | |
| 543 | if (ctx != null) { |
| 544 | boolean originalIsPropertyResolved = ctx.isPropertyResolved(); |
| 545 | try { |
| 546 | T result = ctx.getELResolver().convertToType(ctx, obj, type); |
| 547 | if (ctx.isPropertyResolved()) { |
| 548 | return result; |
| 549 | } |
| 550 | } finally { |
| 551 | ctx.setPropertyResolved(originalIsPropertyResolved); |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | if (type == null || Object.class.equals(type) || (obj != null && type.isAssignableFrom(obj.getClass()))) { |
| 556 | @SuppressWarnings("unchecked") |
| 557 | T result = (T) obj; |
| 558 | return result; |
| 559 | } |
| 560 | |
| 561 | if (!COERCE_TO_ZERO) { |
| 562 | if (obj == null && !type.isPrimitive() && !String.class.isAssignableFrom(type)) { |
| 563 | return null; |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | if (String.class.equals(type)) { |
| 568 | @SuppressWarnings("unchecked") |
| 569 | T result = (T) coerceToString(ctx, obj); |
| 570 | return result; |
| 571 | } |
| 572 | if (ELArithmetic.isNumberType(type)) { |
| 573 | @SuppressWarnings("unchecked") |
| 574 | T result = (T) coerceToNumber(ctx, obj, type); |
| 575 | return result; |
| 576 | } |
| 577 | if (Character.class.equals(type) || Character.TYPE == type) { |
| 578 | @SuppressWarnings("unchecked") |
| 579 | T result = (T) coerceToCharacter(ctx, obj); |
| 580 | return result; |
| 581 | } |
| 582 | if (Boolean.class.equals(type) || Boolean.TYPE == type) { |
| 583 | @SuppressWarnings("unchecked") |
| 584 | T result = (T) coerceToBoolean(ctx, obj, Boolean.TYPE == type); |
| 585 | return result; |
| 586 | } |
| 587 | if (type.isEnum()) { |
| 588 | @SuppressWarnings("unchecked") |
| 589 | T result = (T) coerceToEnum(ctx, obj, type); |
| 590 | return result; |
| 591 | } |
| 592 | |
| 593 | // new to spec |
| 594 | if (obj == null) { |
| 595 | return null; |
| 596 | } |
| 597 | if (obj instanceof String str) { |
| 598 | PropertyEditor editor = PropertyEditorManager.findEditor(type); |