All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.undefinedlabs.scope.jdk.OptionalMapper Maven / Gradle / Ivy

package com.undefinedlabs.scope.jdk;

import com.undefinedlabs.scope.logger.ScopeLogger;
import com.undefinedlabs.scope.logger.ScopeLoggerResolver;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class OptionalMapper {

  private static final ScopeLogger LOGGER = ScopeLoggerResolver.INSTANCE.get();

  private static final String JAVA_OPTIONAL_CLASS_NAME = "java.util.Optional";
  private static final Method Optional_orElse = getOptionalMethod("orElse", Object.class);

  private static Method getOptionalMethod(
      final String methodName, final Class... parameterTypes) {
    try {
      return Class.forName(JAVA_OPTIONAL_CLASS_NAME).getMethod(methodName, parameterTypes);
    } catch (ClassNotFoundException e) {
      LOGGER.warn("Java Optional is not supported: " + e.getMessage());
    } catch (NoSuchMethodException e) {
      LOGGER.warn("Java Optional: dropping support: " + e.getMessage());
    }
    return null;
  }

  private static boolean isJavaOptional(final Class klass) {
    return JAVA_OPTIONAL_CLASS_NAME.equals(klass.getCanonicalName());
  }

  private static boolean isLoadedMethods() {
    return Optional_orElse != null;
  }

  public static Object getByMethod(final Object object, final String method) {
    if (object == null) {
      return null;
    }

    try {
      return OptionalMapper.get(object.getClass().getMethod(method).invoke(object));
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
      throw new IllegalArgumentException("Could not extract value from Object", e);
    }
  }

  public static Object get(final Object optionalObj) {
    if (!isLoadedMethods()) {
      return null;
    }

    if (optionalObj != null && isJavaOptional(optionalObj.getClass())) {
      try {
        return Optional_orElse.invoke(optionalObj, (Object) null);
      } catch (IllegalAccessException | InvocationTargetException e) {
        throw new IllegalArgumentException("Could not extract value from Optional", e);
      }
    }
    return null;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy