Class InvokerHelper

java.lang.Object
org.codehaus.groovy.runtime.InvokerHelper

public class InvokerHelper extends Object
A static helper class to make bytecode generation easier and act as a facade over the Invoker
  • Field Details

  • Constructor Details

    • InvokerHelper

      public InvokerHelper()
  • Method Details

    • removeClass

      public static void removeClass(Class clazz)
      Drops clazz from the meta-class registry, from ClassInfo, and from the Introspector cache.
      Parameters:
      clazz - the class removed from those caches
    • invokeMethodSafe

      public static Object invokeMethodSafe(Object object, String methodName, Object arguments)
      Invokes methodName on object when object is not null. A null receiver returns null and does not call invokeMethod(Object, String, Object).
      Parameters:
      object - the receiver, or null
      methodName - the method to invoke
      arguments - the arguments accepted by invokeMethod(Object, String, Object)
      Returns:
      the method result, or null when object is null
    • invokeStaticMethod

      public static Object invokeStaticMethod(String klass, String methodName, Object arguments) throws ClassNotFoundException
      Loads klass with Class.forName(String) and invokes the static method methodName on that class.
      Parameters:
      klass - the class name passed to Class.forName(String)
      methodName - the static method to invoke
      arguments - the arguments passed to invokeStaticMethod(Class, String, Object)
      Returns:
      the result of the static call
      Throws:
      ClassNotFoundException - if klass cannot be loaded
    • invokeStaticNoArgumentsMethod

      public static Object invokeStaticNoArgumentsMethod(Class type, String methodName)
      Invokes the static method methodName on type with EMPTY_ARGS.
      Parameters:
      type - the class that receives the static call
      methodName - the static method to invoke
      Returns:
      the result of the static call
    • invokeConstructorOf

      public static Object invokeConstructorOf(String klass, Object arguments) throws ClassNotFoundException
      Loads klass with Class.forName(String) and invokes a constructor of that class.
      Parameters:
      klass - the class name passed to Class.forName(String)
      arguments - the arguments passed to invokeConstructorOf(Class, Object)
      Returns:
      the new instance
      Throws:
      ClassNotFoundException - if klass cannot be loaded
    • invokeNoArgumentsConstructorOf

      public static Object invokeNoArgumentsConstructorOf(Class type)
      Invokes a constructor of type with EMPTY_ARGS.
      Parameters:
      type - the class to instantiate
      Returns:
      the new instance
    • invokeClosure

      public static Object invokeClosure(Object closure, Object arguments)
      Invokes doCall on closure through invokeMethod(Object, String, Object).
      Parameters:
      closure - the receiver of doCall
      arguments - the arguments passed to that invocation
      Returns:
      the result of doCall
    • asList

      public static List asList(Object value)
      Adapts value to a List. null becomes Collections.EMPTY_LIST. A List is returned as given. When the runtime class is an array, the value is cast to Object[] and passed to Arrays.asList(T...); a primitive array fails that cast. An Enumeration is copied, in iteration order, into a new ArrayList. Any other value becomes a one-element list. Throws ClassCastException if value is a primitive array.
      Parameters:
      value - the value to adapt
      Returns:
      a list for value
    • getAttribute

      public static Object getAttribute(Object object, String attribute)
      Reads the attribute attribute from object. A null receiver is replaced with NullObject.getNullObject() before the read. A Class receiver is tested before a GroovyObject and uses the meta-class registered for that class. A GroovyObject uses the meta-class from GroovyObject.getMetaClass(). Every other receiver uses the meta-class registered for its runtime class. The value is then read with getAttribute on that meta-class.
      Parameters:
      object - the receiver, or null
      attribute - the attribute name
      Returns:
      the attribute value
    • setAttribute

      public static void setAttribute(Object object, String attribute, Object newValue)
      Writes newValue to the attribute attribute on object. A null receiver is replaced with NullObject.getNullObject() before the write. A Class receiver is tested before a GroovyObject and uses the meta-class registered for that class. A GroovyObject uses the meta-class from GroovyObject.getMetaClass(). Every other receiver uses the meta-class registered for its runtime class. The value is then written with setAttribute on that meta-class.
      Parameters:
      object - the receiver, or null
      attribute - the attribute name
      newValue - the value to assign
    • getProperty

      @GroovyABI(since="2.5.0") public static Object getProperty(Object object, String property)
      Reads the property property from object. A null receiver is replaced with NullObject.getNullObject() before the read. A GroovyObject is tested before a Class and is read through GroovyObject.getProperty(String). A Class receiver uses the meta-class registered for that class. Every other receiver uses MetaClassRegistryImpl.getMetaClass(Object) and then getProperty on that meta-class.
      Parameters:
      object - the receiver, or null
      property - the property name
      Returns:
      the property value
    • getPropertySafe

      @GroovyABI(since="2.5.0") public static Object getPropertySafe(Object object, String property)
      Reads property from object when object is not null. A null receiver returns null and is not replaced with NullObject.
      Parameters:
      object - the receiver, or null
      property - the property name
      Returns:
      the property value, or null when object is null
    • setProperty

      @GroovyABI(since="1.0.0") public static void setProperty(Object object, String property, Object newValue)
      Writes newValue to the property property on object. A null receiver is replaced with NullObject.getNullObject() before the write. A GroovyObject is tested before a Class and is written through GroovyObject.setProperty(String, Object). A Class receiver uses the meta-class registered for that class. Every other receiver uses MetaClassRegistryImpl.getMetaClass(Object) and then setProperty on that meta-class.
      Parameters:
      object - the receiver, or null
      property - the property name
      newValue - the value to assign
    • setProperty2

      @GroovyABI(since="1.0.0") public static void setProperty2(Object newValue, Object object, String property)
      This is so we don't have to reorder the stack when we call this method. At some point a better name might be in order.
    • setGroovyObjectProperty

      @GroovyABI(since="1.0.0") public static void setGroovyObjectProperty(Object newValue, GroovyObject object, String property)
      This is so we don't have to reorder the stack when we call this method. At some point a better name might be in order.
    • getGroovyObjectProperty

      @GroovyABI(since="1.0.0") public static Object getGroovyObjectProperty(GroovyObject object, String property)
      Reads property by calling GroovyObject.getProperty(String) on object, with no null substitution and no registry lookup.
      Parameters:
      object - the Groovy receiver
      property - the property name
      Returns:
      the property value
    • setPropertySafe2

      @GroovyABI(since="1.0.0") public static void setPropertySafe2(Object newValue, Object object, String property)
      This is so we don't have to reorder the stack when we call this method. At some point a better name might be in order.
    • getMethodPointer

      public static Closure getMethodPointer(Object object, String methodName)
      Returns a method closure for the given object and name.
    • unaryMinus

      public static Object unaryMinus(Object value)
      Negates value. Integer, Long, Double, and Float use arithmetic negation. Short and Byte are negated and cast back to short and byte. BigInteger and BigDecimal use negate(). An ArrayList yields a new list of the element-wise results. Any other value is passed to invokeMethod(Object, String, Object) as the no-argument method negative.
      Parameters:
      value - the value to negate
      Returns:
      the negated value
    • unaryPlus

      public static Object unaryPlus(Object value)
      Applies unary plus to value. Integer, Long, BigInteger, BigDecimal, Double, Float, Short, and Byte are returned unchanged. An ArrayList yields a new list of the element-wise results. Any other value is passed to invokeMethod(Object, String, Object) as the no-argument method positive.
      Parameters:
      value - the value to which unary plus is applied
      Returns:
      the numeric value unchanged, or the element-wise or method result
    • findRegex

      public static Matcher findRegex(Object left, Object right)
      Find the right hand regex within the left hand string and return a matcher.
      Parameters:
      left - string to compare
      right - regular expression to compare the string to
    • matchRegex

      public static boolean matchRegex(Object left, Object right)
      Find the right hand regex within the left hand string and return a matcher.
      Parameters:
      left - string to compare
      right - regular expression to compare the string to
    • createTuple

      public static Tuple createTuple(Object[] array)
      Returns a Tuple constructed from array.
      Parameters:
      array - the elements passed to the tuple constructor
      Returns:
      the new tuple
    • spreadMap

      public static SpreadMap spreadMap(Object value)
      Builds a SpreadMap from value when value is a Map. Entries are flattened, in key-set iteration order, into an array that alternates key then value, and that array is passed to the SpreadMap constructor. A non-map value throws SpreadMapEvaluatingException. null does not reach that throw: the message calls FormatHelper.typeName(value), which dereferences value.
      Parameters:
      value - the map to spread
      Returns:
      a spread map of the map's entries
    • createList

      public static List createList(Object[] values)
      Returns a new ArrayList sized to values.length and filled with those elements in order.
      Parameters:
      values - the elements to copy into the list
      Returns:
      the new list
    • initialCapacity

      public static int initialCapacity(int initialEntryCnt)
      According to the initial entry count, calculate the initial capacity of hash map, which is power of 2 (SEE https://stackoverflow.com/questions/8352378/why-does-hashmap-require-that-the-initial-capacity-be-a-power-of-two)
      Parameters:
      initialEntryCnt - the initial entry count
      Returns:
      the initial capacity
    • createMap

      public static Map createMap(Object[] values)
      Builds a LinkedHashMap from successive pairs in values. The initial capacity is initialCapacity(int) of values.length / 2. A pair whose first element is a SpreadMap and whose second element is a Map contributes that map's entries. Every other pair is stored as one key and value. A trailing element left without a pair is ignored.
      Parameters:
      values - alternating keys and values, with optional spread pairs
      Returns:
      the collected entries in insertion order
    • assertFailed

      public static void assertFailed(Object expression, Object message)
      Throws the AssertionError returned by createAssertError(Object, Object) for expression and message.
      Parameters:
      expression - the expression supplied to the error
      message - the message supplied to the error
    • createAssertError

      public static AssertionError createAssertError(Object expression, Object message)
      Since:
      4.0.7
    • runScript

      public static Object runScript(Class scriptClass, String[] args)
      Runs scriptClass in a Binding whose args variable is the supplied array. The instance comes from createScript(Class, Binding), and run is invoked on it with EMPTY_ARGS.
      Parameters:
      scriptClass - the class passed to createScript(Class, Binding)
      args - the array stored as the binding variable args
      Returns:
      the result of run
    • createScript

      public static Script createScript(Class scriptClass, Binding context)
      Adapts scriptClass to a Script associated with context.

      A null class produces a NullScript bound to context; its run method returns null. A class assignable to Script is instantiated with newScript(Class, Binding).

      For any other class, Binding.class.getName() is loaded from scriptClass's class loader. A binding of that loaded type is constructed from context.getVariables() through its declared Map constructor, and scriptClass is constructed with its declared constructor that takes that binding type. The instance is wrapped in a Script created with the no-argument constructor, so the wrapper's own binding is a new empty Binding. The wrapper's run method invokes run on the instance with no arguments.

      If that attempt throws ClassNotFoundException, NoSuchMethodException, or SecurityException, the result is a Script constructed with context. Its run method calls the static MAIN_METHOD_NAME method with one argument: the binding property args when that value is a String[], otherwise a new empty String[]. A missing args property, reported as MissingPropertyException, also selects the empty array. Before the wrapper is returned, each entry of context.getVariables() whose key's toString() does not start with '_' is written as a property of the scriptClass class object. A MissingPropertyException from that write is ignored, and so is an IllegalArgumentException carried as the cause of an InvokerInvocationException.

      Any other Exception is wrapped in a GroovyRuntimeException that names scriptClass.

      Parameters:
      scriptClass - the class to adapt, or null
      context - the binding supplied to the adapted script
      Returns:
      the adapted Script
    • newScript

      public static Script newScript(Class<? extends Script> scriptClass, Binding context) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException
      Instantiates scriptClass and associates context. Uses the public (Binding) constructor when scriptClass has one. When that constructor is absent, calls the declared no-argument constructor and then Script.setBinding(Binding).
      Parameters:
      scriptClass - the Script type to construct
      context - the binding passed to the constructor, or to setBinding
      Returns:
      the new script instance
      Throws:
      NoSuchMethodException - if the no-argument constructor is absent
      InstantiationException - if the class that declares the chosen constructor is abstract
      IllegalAccessException - if the chosen constructor is inaccessible
      InvocationTargetException - if the chosen constructor throws an exception
    • setProperties

      public static void setProperties(Object object, Map map)
      Sets the properties on the given object
    • createRange

      public static List createRange(Object from, Object to, boolean exclusiveLeft, boolean exclusiveRight)
      Creates the range from from to to by delegating to ScriptBytecodeAdapter.createRange. A RuntimeException or Error is rethrown unchanged. Any other Throwable is wrapped in a RuntimeException.
      Parameters:
      from - the start value passed to the delegate
      to - the end value passed to the delegate
      exclusiveLeft - passed through as the left-exclusive flag
      exclusiveRight - passed through as the right-exclusive flag
      Returns:
      the list returned by the delegate
    • createRange

      public static List createRange(Object from, Object to, boolean inclusive)
      Creates a range from from to to with the left end included. The call is createRange(from, to, false, !inclusive), so inclusive controls whether to is included.
      Parameters:
      from - the start value; the left end is inclusive
      to - the end value
      inclusive - true to include to; false to exclude it
      Returns:
      the list from createRange(Object, Object, boolean, boolean)
    • bitwiseNegate

      public static Object bitwiseNegate(Object value)
      Bitwise-negates value. Integer and Long use the ~ operator. BigInteger uses not(). A String or GString is compiled as a regular expression by StringGroovyMethods.bitwiseNegate on value.toString(). An ArrayList yields a new list of the element-wise results. Any other value is passed to invokeMethod(Object, String, Object) as the no-argument method bitwiseNegate.
      Parameters:
      value - the value to negate
      Returns:
      the negated number, the Pattern compiled from a string or GString, a list of the element-wise results, or the value returned by the no-argument bitwiseNegate method
    • getMetaRegistry

      public static MetaClassRegistry getMetaRegistry()
      Returns metaRegistry.
      Returns:
      the registry from GroovySystem.getMetaClassRegistry()
    • getMetaClass

      public static MetaClass getMetaClass(Object object)
      Returns the meta-class used for object. A GroovyObject is tested before a Class and answers with GroovyObject.getMetaClass(). A Class answers with MetaClassRegistry.getMetaClass(Class) on metaRegistry. Any other object answers with MetaClassRegistryImpl.getMetaClass(Object).
      Parameters:
      object - the receiver whose meta-class is required
      Returns:
      that meta-class
    • getMetaClass

      public static MetaClass getMetaClass(Class cls)
      Returns the meta-class registered for cls.
      Parameters:
      cls - the class to look up in metaRegistry
      Returns:
      MetaClassRegistry.getMetaClass(Class) for cls
    • invokeMethod

      @GroovyABI(since="5.0.0") public static Object invokeMethod(Object object, String methodName, Object arguments)
      Invokes the given method on the object.
    • invokeSuperMethod

      public static Object invokeSuperMethod(Object object, String methodName, Object arguments)
      Invokes methodName through the meta-class of the superclass of object's runtime class. Arguments are normalized with asArray(Object). A null receiver throws NullPointerException whose message names methodName.
      Parameters:
      object - the receiver; must not be null
      methodName - the method to invoke
      arguments - the argument list, a single argument, or null
      Returns:
      the result of the meta-class invocation
    • invokeStaticMethod

      public static Object invokeStaticMethod(Class type, String method, Object arguments)
      Invokes the static method method on type through the meta-class registered for type. Arguments are normalized with asArray(Object).
      Parameters:
      type - the class that receives the static call
      method - the method name
      arguments - the argument list, a single argument, or null
      Returns:
      the result of the static call
    • invokeConstructorOf

      public static Object invokeConstructorOf(Class type, Object arguments)
      Invokes a constructor of type through the meta-class registered for that class. Arguments are normalized with asArray(Object).
      Parameters:
      type - the class to instantiate
      arguments - the argument list, a single argument, or null
      Returns:
      the new instance
    • asArray

      public static Object[] asArray(Object arguments)
      Converts the given object into an array; if it's an array then just cast otherwise wrap it in an array
    • asUnwrappedArray

      public static Object[] asUnwrappedArray(Object arguments)
      Normalizes arguments with asArray(Object), then replaces each PojoWrapper element with PojoWrapper.unwrap(). When arguments is already an Object[], that same array is updated and returned.
      Parameters:
      arguments - the argument list, a single argument, or null
      Returns:
      the normalized array, with wrappers removed
    • asIterator

      public static Iterator<Object> asIterator(Object o)
      Invokes the no-argument method iterator on o and casts the result to Iterator.
      Parameters:
      o - the receiver of iterator
      Returns:
      the iterator returned by that call
    • toString

      @Deprecated @GroovyABI(since="1.0.0") public static String toString(Object arguments)
      Deprecated.
      use FormatHelper.toString(Object)
      Returns the string representation of arguments produced by FormatHelper.toString(Object).
      Parameters:
      arguments - the object to render
      Returns:
      that string representation
    • inspect

      @Deprecated public static String inspect(Object self)
      Deprecated.
      use FormatHelper.inspect(Object)
      Returns the inspect rendering of self produced by FormatHelper.inspect(Object), which selects inspect mode with escaped backslashes.
      Parameters:
      self - the object to inspect
      Returns:
      that rendering
    • write

      @Deprecated public static void write(Writer out, Object object) throws IOException
      Deprecated.
      use FormatHelper.write(Writer, Object)
      Writes object to out by calling FormatHelper.write(Writer, Object).
      Parameters:
      out - the writer that receives the text
      object - the object to write
      Throws:
      IOException - if writing fails
    • append

      @Deprecated public static void append(Appendable out, Object object) throws IOException
      Deprecated.
      use FormatHelper.append(Appendable, Object)
      Appends object to out by calling FormatHelper.append(Appendable, Object).
      Parameters:
      out - the appendable that receives the text
      object - the object to append
      Throws:
      IOException - if appending fails
    • format

      @Deprecated protected static String format(Object arguments, boolean verbose)
      Deprecated.
      use FormatHelper.format(Object, boolean)
      Renders arguments by calling FormatHelper.format(Object, boolean). When verbose is true, the delegate uses inspect mode with escaped backslashes.
      Parameters:
      arguments - the object to render
      verbose - true to select inspect mode with escaped backslashes
      Returns:
      the formatted text
    • format

      @Deprecated public static String format(Object arguments, boolean verbose, int maxSize)
      Deprecated.
      use FormatHelper.format(Object, boolean, int)
      Renders arguments by calling FormatHelper.format(Object, boolean, int). When verbose is true, the delegate uses inspect mode with escaped backslashes. maxSize is an approximate character limit; -1 means no limit.
      Parameters:
      arguments - the object to render
      verbose - true to select inspect mode with escaped backslashes
      maxSize - the approximate character limit, or -1 for no limit
      Returns:
      the formatted text
    • format

      @Deprecated public static String format(Object arguments, boolean verbose, int maxSize, boolean safe)
      Deprecated.
      use FormatHelper.format(Object, boolean, int, boolean)
      Renders arguments by calling FormatHelper.format(Object, boolean, int, boolean). When verbose is true, the delegate uses inspect mode with escaped backslashes. maxSize is an approximate character limit; -1 means no limit. When safe is true, an Exception thrown while rendering is swallowed and a fallback representation is used.
      Parameters:
      arguments - the object to render
      verbose - true to select inspect mode with escaped backslashes
      maxSize - the approximate character limit, or -1 for no limit
      safe - true to swallow a rendering Exception
      Returns:
      the formatted text
    • escapeBackslashes

      @Deprecated public static String escapeBackslashes(String orig)
      Deprecated.
      use FormatHelper.escapeBackslashes(String)
      Returns orig with backslash, newline, carriage return, tab, and form feed written as escape sequences, by calling FormatHelper.escapeBackslashes(String).
      Parameters:
      orig - the text to escape
      Returns:
      the escaped text
    • toTypeString

      @Deprecated public static String toTypeString(Object[] arguments)
      Deprecated.
      use FormatHelper.toTypeString(Object[])
      Returns a comma-separated list of the runtime type names in arguments, by calling FormatHelper.toTypeString(Object[]).
      Parameters:
      arguments - the values whose types are rendered
      Returns:
      the type list, or "null" when arguments is null
    • toTypeString

      @Deprecated public static String toTypeString(Object[] arguments, int maxSize)
      Deprecated.
      use FormatHelper.toTypeString(Object[], int)
      Returns a comma-separated list of the runtime type names in arguments, by calling FormatHelper.toTypeString(Object[], int). Output stops after about maxSize characters and then appends "..."; -1 means no limit.
      Parameters:
      arguments - the values whose types are rendered
      maxSize - the approximate character limit, or -1 for no limit
      Returns:
      the type list
    • toMapString

      @Deprecated public static String toMapString(Map arg)
      Deprecated.
      use FormatHelper.toMapString(Map)
      Returns the bracketed rendering of arg, using [ and ] boundaries, by calling FormatHelper.toMapString(Map).
      Parameters:
      arg - the map to render
      Returns:
      the map text
    • toMapString

      @Deprecated public static String toMapString(Map arg, int maxSize)
      Deprecated.
      use FormatHelper.toMapString(Map, int)
      Returns the bracketed rendering of arg, using [ and ] boundaries, by calling FormatHelper.toMapString(Map, int). Output stops after about maxSize characters and then appends "..."; -1 means no limit.
      Parameters:
      arg - the map to render
      maxSize - the approximate character limit, or -1 for no limit
      Returns:
      the map text
    • toListString

      @Deprecated public static String toListString(Collection arg)
      Deprecated.
      use FormatHelper.toListString(Collection)
      Returns the bracketed rendering of arg, using [ and ] boundaries, by calling FormatHelper.toListString(Collection).
      Parameters:
      arg - the collection to render
      Returns:
      the collection text
    • toListString

      @Deprecated public static String toListString(Collection arg, int maxSize)
      Deprecated.
      use FormatHelper.toListString(Collection, int)
      Returns the bracketed rendering of arg, using [ and ] boundaries, by calling FormatHelper.toListString(Collection, int). Output stops after about maxSize characters and then appends "..."; -1 means no limit.
      Parameters:
      arg - the collection to render
      maxSize - the approximate character limit, or -1 for no limit
      Returns:
      the collection text
    • toListString

      @Deprecated public static String toListString(Collection arg, int maxSize, boolean safe)
      Deprecated.
      use FormatHelper.toListString(Collection, int, boolean)
      Returns the bracketed rendering of arg, using [ and ] boundaries, by calling FormatHelper.toListString(Collection, int, boolean). Output stops after about maxSize characters and then appends "..."; -1 means no limit. When safe is true, an item whose rendering throws an Exception uses a fallback representation.
      Parameters:
      arg - the collection to render
      maxSize - the approximate character limit, or -1 for no limit
      safe - true to substitute a fallback for an item that fails to render
      Returns:
      the collection text
    • toArrayString

      @Deprecated public static String toArrayString(Object[] arguments)
      Deprecated.
      use FormatHelper.toArrayString(Object[])
      Returns the bracketed rendering of arguments, using [ and ] boundaries, by calling FormatHelper.toArrayString(Object[]).
      Parameters:
      arguments - the array to render
      Returns:
      the array text
    • toArrayString

      @Deprecated public static String toArrayString(Object[] arguments, int maxSize, boolean safe)
      Deprecated.
      use FormatHelper.toArrayString(Object[], int, boolean)
      Returns the bracketed rendering of arguments, using [ and ] boundaries, by calling FormatHelper.toArrayString(Object[], int, boolean). Output stops after about maxSize characters and then appends "..."; -1 means no limit. When safe is true, an element whose rendering throws an Exception uses a fallback representation.
      Parameters:
      arguments - the array to render
      maxSize - the approximate character limit, or -1 for no limit
      safe - true to substitute a fallback for an element that fails to render
      Returns:
      the array text