+ return cast(RuntimeNamespaceContext.getNamespaceContext(), clss, value);
+ }
+
+ /**
+ * Cast well know java types based on {@link Object#toString()} of the provided
+ * object.
+ *
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> Optional<T> cast(NamespaceContext namespaceContext, Class<T> clss, Object value) {
+ // if value is null, optional is empty
+ if (value == null)
+ return Optional.empty();
+
+ // if a default has been explicitly requested by passing Object.class
+ // we parse the related String
+ if (clss.isAssignableFrom(Object.class)) {
+ return Optional.of((T) parse(value.toString()));
+ }
+
+ // if value can be cast directly, let's do it
+ if (value.getClass().isAssignableFrom(clss)) {
+ return Optional.of(((T) value));
+ }
+
+ // let's cast between various numbers (possibly losing precision)
+ if (value instanceof Number number) {
+ if (Long.class.isAssignableFrom(clss))
+ return Optional.of((T) (Long) number.longValue());
+ else if (Integer.class.isAssignableFrom(clss))
+ return Optional.of((T) (Integer) number.intValue());
+ else if (Double.class.isAssignableFrom(clss))
+ return Optional.of((T) (Double) number.doubleValue());
+ }
+
+ // let's now try with the string representation
+ String strValue = value instanceof String ? (String) value : value.toString();
+