Class JavaClosure

All Implemented Interfaces:
Proxy

@NullMarked public class JavaClosure extends Closure
An implementation of Closure that can be used with Java callbacks. In most cases, the callback will be invoked using reflection. For two common cases (Runnable and BooleanSupplier), the callback will be invoked directly.
  • Constructor Details

    • JavaClosure

      public JavaClosure(Runnable callback)
      Construct a Closure for a method or lambda that takes no parameters and returns void.
      Parameters:
      callback - a callback with signature void run()
    • JavaClosure

      public JavaClosure(BooleanSupplier callback)
      Construct a Closure for a method or lambda that takes no parameters and returns boolean.
      Parameters:
      callback - a callback with signature boolean run()
    • JavaClosure

      public JavaClosure(Object lambda) throws IllegalArgumentException
      Construct a Closure that will invoke the provided Java lambda using reflection. The Closure function arguments are read from the argument-Value containers and passed to the lambda. The return value of the lambda is put in the Closure return-Value.
      Parameters:
      lambda - a lambda (instance of a functional interface)
      Throws:
      IllegalArgumentException - if the lambda is not an instance of a functional interface
    • JavaClosure

      public JavaClosure(@Nullable Object instance, Method method)
      Construct a Closure that will invoke the provided Java method using reflection. The Closure function arguments are read from the argument-Value containers and passed to the method. The return value of the method is put in the Closure return-Value.
      Parameters:
      instance - a class instance on which the provided method will be invoked. When the method is static, this parameter is ignored and and may be null.
      method - the method to invoke. See Method.invoke(Object, Object...)
  • Method Details

    • ignoreFirstParameter

      public JavaClosure ignoreFirstParameter()
      Ignore the first parameter of the closure. This is often the source of an event, a property binding, or something else that is not included in the Java API, so this option specifies to ignore it.
      Returns:
      this JavaClosure
    • getSingleMethod

      public static Method getSingleMethod(Class<?> cls) throws IllegalArgumentException
      Get the single abstract method (SAM) implementation of a class that implements a functional interface. A functional interface is an interface with exactly one abstract method.
      Parameters:
      cls - a functional interface
      Returns:
      the Method reference to the method that implements the SAM
      Throws:
      IllegalArgumentException - if cls is not a functional interface