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

com.kirekov.sneaky.Sneaky Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.kirekov.sneaky;

import com.kirekov.sneaky.lambda.CheckedBiConsumer;
import com.kirekov.sneaky.lambda.CheckedConsumer;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * Factory for sneaky wrappers.
 */
public final class Sneaky {

  private Sneaky() {
    // no op
  }


  /**
   * Returns {@linkplain Consumer} that may throw {@linkplain Exception} ignoring {@code throws
   * Exception} in the method signature.
   *
   * @param checkedConsumer consumer that throws {@linkplain Exception}
   * @param              the input argument
   * @return wrapped consumer
   */
  public static  Consumer consumer(CheckedConsumer checkedConsumer) {
    return value -> {
      try {
        checkedConsumer.accept(value);
      } catch (Exception e) {
        throwUnchecked(e);
      }
    };
  }

  /**
   * Returns {@linkplain BiConsumer} that may throw {@linkplain Exception} ignoring {@code throws
   * Exception} in the method signature.
   *
   * @param checkedBiConsumer biConsumer that throws {@linkplain Exception}
   * @param                the first input argument
   * @param                the second input argument
   * @return wrapped biConsumer
   */
  public static  BiConsumer biConsumer(CheckedBiConsumer checkedBiConsumer) {
    return (t, u) -> {
      try {
        checkedBiConsumer.accept(t, u);
      } catch (Exception e) {
        throwUnchecked(e);
      }
    };
  }

  /**
   * Throws {@linkplain Exception}. Does not require adding {@code throws Exception} to a method
   * signature.
   *
   * @param exception exception to throw
   * @param        the type of the exception to throw
   * @throws T exception throw. Due to Java generic erasure the actual type is always {@linkplain
   *           Exception}
   */
  @SuppressWarnings("unchecked")
  public static  void throwUnchecked(Exception exception) throws T {
    throw (T) exception;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy