code: public static <T> Optional<T> cast(final Object o, final Class<T> clazz) {
          T result = null;
          /*
           * There is no null pointer checking for clazz to detect logic errors.
           */
          if (o != null && clazz.isInstance(o)) {
              result = (T) o;
          }
          return Optional.ofNullable(result);
      }
docs: Cast object to clazz and returns Optional. If it can not be cast then the Optional is empty.
  @param <T> type to cast to
  @param o object to cast
  @param clazz type of value class to cast to
  @return optional value of type T