Class MetaClassHelper

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

public class MetaClassHelper extends Object
Helpers for choosing a meta-method and for the argument-distance used by that choice.
  • Field Details

    • EMPTY_ARRAY

      public static final Object[] EMPTY_ARRAY
      Shared zero-length array for a call that passes no arguments.
    • EMPTY_TYPE_ARRAY

      public static final Class[] EMPTY_TYPE_ARRAY
      Shared zero-length class array for a signature with no parameters.
    • EMPTY_CLASS_ARRAY

      public static final Class[] EMPTY_CLASS_ARRAY
      Shared zero-length class array, the same instance as EMPTY_TYPE_ARRAY.
    • ARRAY_WITH_NULL

      public static final Object[] ARRAY_WITH_NULL
      Shared one-element array whose only slot is null. The array is mutable: a write to the slot is visible to every user of this field.
  • Constructor Details

    • MetaClassHelper

      public MetaClassHelper()
  • Method Details

    • accessibleToConstructor

      public static boolean accessibleToConstructor(Class at, Constructor constructor)
      Tests whether at can access constructor under the visibility rules applied here. A public constructor is accessible. A private constructor is accessible when the binary name of at equals Constructor.getName(), which is the binary name of the declaring class. A protected constructor is accessible when at and the declaring class are in the same package, the unnamed package included. When both classes have named packages and those packages differ, it is accessible when the declaring class is at or a superclass of at. A package-private constructor is accessible in that same-package case, with no superclass exception. A class in the unnamed package and a class in a named package are treated as different packages for both of those modifiers.
      Parameters:
      at - the class attempting the access
      constructor - the constructor being accessed
      Returns:
      true when the visibility rule for the constructor's modifiers accepts at
    • asWrapperArray

      public static Object[] asWrapperArray(Object parameters, Class componentType)
      Boxes a primitive array into a new Object array. parameters is cast to the primitive array named by componentType, and each element is boxed. The component types handled are boolean, char, byte, short, int, long, float, and double. Any other component type, null included, produces null and leaves parameters unread.
      Parameters:
      parameters - a primitive array of component type componentType
      componentType - the primitive component type of parameters
      Returns:
      a new array of boxed elements, or null when componentType is not one of those eight primitives
    • asPrimitiveArray

      public static Object asPrimitiveArray(List list, Class parameterType)
      Parameters:
      list - the original list
      parameterType - the resulting array type
      Returns:
      the constructed array
    • dependsOnMethodClosureArity

      public static boolean dependsOnMethodClosureArity(Object methodOrList, Class[] types, Object[] arguments)
      Tells whether choosing among methodOrList for these arguments depends on the method closures among them, beyond their class: whether a method closure is passed where the valid candidates take functional interfaces of different arity, as a method reference can implement only an interface whose abstract method it can be called with. Such a choice must not be cached by argument classes.
      Parameters:
      methodOrList - the overload set, as a FastArray of ParameterTypes; any other value makes this method return false
      types - argument classes passed to ParameterTypes.isValidMethod(Class[]); null makes this method return false
      arguments - the call arguments. A MethodClosure is compared with the SAM arity of the functional-interface parameter at the same index. null makes this method return false
      Returns:
      true when two candidates that are still valid for types accept a method closure at the same position through functional interfaces whose abstract methods take different numbers of parameters
      Since:
      6.0.1
    • filterByMethodClosureArity

      public static <M> List<M> filterByMethodClosureArity(List<M> candidates, Object[] arguments)
      Drops the candidates with a functional-interface parameter whose abstract method takes a number of arguments the method closure passed there cannot be called with; keeps every candidate if none fits.
      Type Parameters:
      M - the candidate type. Each element is read as ParameterTypes
      Parameters:
      candidates - the overload candidates to filter
      arguments - the call arguments. A candidate is kept only when the functional-interface parameter at the index of each MethodClosure has an abstract method the closure can be called with
      Returns:
      the candidates that accept those method closures, or candidates itself when none of them fit
      Since:
      6.0.1
    • calculateParameterDistance

      public static long calculateParameterDistance(Class[] arguments, ParameterTypes pt)
      Scores how far arguments are from the parameters of pt. A smaller non-negative score is a closer match. A negative score means an interface parameter the argument does not implement. An empty parameter list scores 0.

      Every parameter except the last contributes one term for the argument in that position. An exact class match scores 0, as does a class assignable to GeneratedClosure passed to Closure. An interface parameter scores the longest path through superclasses and superinterfaces, and scores a negative value when no such path exists. A Closure that does not implement the interface is scored as an object instead, with a lower score when its doCall count matches the single abstract method. A class that declares more than one doCall matches an abstract method of zero or one parameter. Two types that are both in this class's primitive-distance table (the primitives, their wrappers, BigInteger, BigDecimal, Number, and Object) contribute that table's conversion distance. Any other pair contributes a superclass walk from the argument toward the parameter, plus a further penalty when an array is passed to a non-array parameter. The walk stops early when GString is passed to String. A null argument scores 0 for NullObject and 1 for Object; otherwise the score is the distance from the parameter up to Object. A null argument passed to an interface uses a small fixed interface distance instead.

      The last parameter is then treated as a possible varargs parameter. The varargs penalty occupies higher bits than those per-argument terms, so a non-varargs fit outranks every varargs fit, and a varargs fit that consumes fewer arguments outranks one that consumes more. Equal lengths with the last argument Java-assignable to the last parameter, null counting as assignable, add no penalty, and that argument is scored against the last parameter. Fewer arguments than parameters add one penalty unit and leave the missing tail unscored. Equal lengths where the last argument is not assignable to the last parameter add two penalty units, and that argument is scored against the parameter's component type. More arguments than parameters add two penalty units plus one unit per extra argument, and every argument from the last parameter onward is scored against that parameter's component type.

      Parameters:
      arguments - classes of the call arguments, in order; a null entry is a null argument
      pt - the candidate parameter list
      Returns:
      the packed distance; a smaller non-negative value is a closer fit
    • capitalize

      @Deprecated(forRemoval=true, since="3.0.0") public static String capitalize(String property)
      Deprecated, for removal: This API element is subject to removal in a future version.
    • chooseEmptyMethodParams

      public static Object chooseEmptyMethodParams(FastArray methods)
      Parameters:
      methods - the methods to choose from
      Returns:
      the method with 1 parameter which takes the most general type of object (e.g. Object)
    • chooseMostGeneralMethodWith1NullParam

      @Deprecated public static Object chooseMostGeneralMethodWith1NullParam(FastArray methods)
      Deprecated.
      Warning: this method does not choose properly if multiple methods with the same distance are encountered
      Parameters:
      methods - the methods to choose from
      Returns:
      the method with 1 parameter which takes the most general type of object (e.g. Object) ignoring primitive types
    • containsMatchingMethod

      public static boolean containsMatchingMethod(List list, MetaMethod method)
      Parameters:
      list - a list of MetaMethods
      method - the MetaMethod of interest
      Returns:
      true if a method of the same matching prototype was found in the list
    • convertToTypeArray

      public static Class[] convertToTypeArray(Object[] arguments)
      Converts array of values (incl. null) to their respective types.
      Parameters:
      arguments - the arguments
      Returns:
      the types of the arguments
    • makeCommonArray

      public static Object makeCommonArray(Object[] arguments, int offset, Class fallback)
      Copies arguments from offset to the end into a new array whose component type is shared by that range. Null elements are skipped while the type is chosen. The type starts as the class of the first non-null element and walks toward Object until Class.isAssignableFrom(Class) accepts every later non-null element. A range of only nulls uses fallback. When the chosen class is Object and fallback is an interface, the interface is used instead when every slot in the range is non-null and, for each element, fallback is a direct interface of that element's class or of a superclass below Object.
      Parameters:
      arguments - the source values; elements before offset are ignored
      offset - the first index copied into the result
      fallback - component type of an all-null range, and the interface tried when the common class is Object
      Returns:
      the array of the chosen component type holding the copied elements
    • makeArray

      public static Object makeArray(Object obj, Class secondary, int length)
      Allocates an array of the given length. The component type is the runtime class of obj when obj is non-null, and secondary when it is null. The new array is empty; obj is not stored in it.
      Parameters:
      obj - instance whose class supplies the component type, or null
      secondary - component type used when obj is null
      length - the requested array length
      Returns:
      a new array of that component type and length
    • createExceptionText

      public static GroovyRuntimeException createExceptionText(String init, MetaMethod method, Object object, Object[] args, Throwable reason, boolean setReason)
      Builds a GroovyRuntimeException describing a failed meta-method call. The message is init, the method, " on: ", the receiver object, " with arguments: ", FormatHelper.toString(args), " reason: ", and reason, concatenated in that order. When setReason is true, reason is also the exception cause; when it is false, the cause is left null. This method returns the exception and does not throw it.
      Parameters:
      init - text that opens the message
      method - the meta-method that failed
      object - the receiver the method was invoked on
      args - the arguments passed to the method
      reason - the failure to report
      setReason - whether reason is attached as the cause
      Returns:
      the populated exception
    • getClassName

      protected static String getClassName(Object object)
      Returns the binary name associated with object. A null argument returns null. A Class contributes its own name, rather than the name java.lang.Class. Every other value contributes the name of its runtime class.
      Parameters:
      object - a class, an instance, or null
      Returns:
      the binary name, or null when object is null
    • getMethodPointer

      public static Closure getMethodPointer(Object object, String methodName)
      Returns a callable object for the given method name on the object. The object acts like a Closure in that it can be called, like a closure and passed around - though really it's a method pointer, not a closure per se.
      Parameters:
      object - the object containing the method
      methodName - the method of interest
      Returns:
      the resulting closure-like method pointer
    • isAssignableFrom

      public static boolean isAssignableFrom(Class classToTransformTo, Class classToTransformFrom)
      Tests whether a value of classToTransformFrom may be passed where classToTransformTo is expected, including Groovy coercions beyond Class.isAssignableFrom(Class). A null source is accepted for every target, and a target of Object accepts every source. Both classes are boxed before the remaining checks, so a primitive and its wrapper match. boolean and char take part through boxing and ordinary assignability. The further coercions are: Every other pair uses Class.isAssignableFrom(Class) on the boxed classes.
      Parameters:
      classToTransformTo - the destination type
      classToTransformFrom - the source type, or null
      Returns:
      true when the source may be used as the destination
    • isSuperclass

      protected static boolean isSuperclass(Class clazz, Class superclass)
      Walks clazz and then each superclass, looking for superclass. The walk includes clazz itself, so a class counts as a superclass of itself here. A null clazz ends the walk immediately.
      Parameters:
      clazz - the class whose superclass chain is examined, or null
      superclass - the class to find on that chain
      Returns:
      true when superclass is clazz or a superclass of it
    • parametersAreCompatible

      public static boolean parametersAreCompatible(Class[] arguments, Class[] parameters)
      Tests whether each argument class is acceptable for the parameter class in the same position, using isAssignableFrom(Class, Class). The arrays must have the same length; a shorter or longer argument list is incompatible, varargs included.
      Parameters:
      arguments - the runtime argument classes
      parameters - the formal parameter classes
      Returns:
      true when the lengths match and each argument is assignable to its parameter
    • logMethodCall

      public static void logMethodCall(Object object, String methodName, Object[] arguments)
      Logs an invocation at Level.FINER when that level is enabled for the call's logger. The logger name is methodCalls. followed by getClassName(Object) of object and methodName; a null receiver is concatenated as the text null. The log record's source method is methodName plus the arguments rendered by normalizedValue(Object), separated by commas. A null arguments array produces an empty pair of parentheses. The log message is called from MetaClass.invokeMethod. A logger that is not at Level.FINER returns before the message is built.
      Parameters:
      object - the receiver, used in the logger name
      methodName - the method that was invoked
      arguments - the arguments, or null when there are none to render
    • normalizedValue

      protected static String normalizedValue(Object argument)
      Renders one argument for logMethodCall(Object, String, Object[]). The text is Object.toString(). When that text is longer than twelve characters, the first ten are kept and .. is appended. A String is then wrapped in single quotes. When toString throws, the result is shortName(Object) instead, which is also the result for a null argument.
      Parameters:
      argument - the value to render, or null
      Returns:
      the truncated text, quoted when the value is a String, or the short-name fallback
    • shortName

      protected static String shortName(Object object)
      Returns a simple name of object for a log line. A null argument, or an argument whose class is null, yields unknownClass. Otherwise the binary name from getClassName(Object) is used: a Class contributes its own name, and any other value contributes its runtime class name. When that name contains a '.' with at least one character after it, the substring after the last dot is returned. A missing binary name yields unknownClassName.
      Parameters:
      object - the value whose class name is shortened, or null
      Returns:
      the simple name, unknownClass, or unknownClassName
    • wrap

      public static Class[] wrap(Class[] classes)
      Copies classes, boxing selected primitives and rewriting GString types to String. A null entry stays null. int, byte, long, double, and float become the matching wrapper class. boolean, char, short, and void stay primitive. A type that is GString or a subclass of it becomes String. Every other class is copied unchanged.
      Parameters:
      classes - the classes to adapt; entries may be null
      Returns:
      a new array of the same length with those substitutions
    • sameClasses

      public static boolean sameClasses(Class[] params, Object[] arguments, boolean weakNullCheck)
      Tests whether each parameter class is identical to the class derived from the argument in the same position. The arrays must have the same length. A null argument matches a null parameter class. A Wrapper is represented by Wrapper.getType(), and every other argument by Object.getClass(). weakNullCheck is not consulted; null and non-null arguments share this comparison.
      Parameters:
      params - the parameter classes, null slots included
      arguments - the call arguments
      weakNullCheck - unused
      Returns:
      true when the lengths match and every slot matches by identity
    • sameClasses

      public static boolean sameClasses(Class[] params, Object[] arguments)
      Tests whether each parameter class is identical to the class derived from the argument in the same position. The arrays must have the same length. A null argument matches a null parameter class. A Wrapper is represented by Wrapper.getType(), and every other argument by Object.getClass().
      Parameters:
      params - the parameter classes, null slots included
      arguments - the call arguments
      Returns:
      true when the lengths match and every slot matches by identity
    • sameClasses

      public static boolean sameClasses(Class[] params)
      Tests a call that passed no arguments against params. No class is compared; the result is whether the array is empty.
      Parameters:
      params - the parameter classes of the candidate signature
      Returns:
      true when params has length zero
    • sameClasses

      public static boolean sameClasses(Class[] params, Object arg1)
      Tests a one-argument call. params must have length one, and its only class must be identical to the class of arg1. A null argument matches a null parameter class, and a Wrapper is represented by Wrapper.getType().
      Parameters:
      params - the parameter classes; the length must be one
      arg1 - the sole argument, or null
      Returns:
      true when the length is one and the class matches by identity
    • sameClasses

      public static boolean sameClasses(Class[] params, Object arg1, Object arg2)
      Tests a two-argument call. params must have length two, and each class must be identical to the class of the argument in that position. A null argument matches a null parameter class, and a Wrapper is represented by Wrapper.getType().
      Parameters:
      params - the parameter classes; the length must be two
      arg1 - the first argument, or null
      arg2 - the second argument, or null
      Returns:
      true when the length is two and both classes match by identity
    • sameClasses

      public static boolean sameClasses(Class[] params, Object arg1, Object arg2, Object arg3)
      Tests a three-argument call. params must have length three, and each class must be identical to the class of the argument in that position. A null argument matches a null parameter class, and a Wrapper is represented by Wrapper.getType().
      Parameters:
      params - the parameter classes; the length must be three
      arg1 - the first argument, or null
      arg2 - the second argument, or null
      arg3 - the third argument, or null
      Returns:
      true when the length is three and every class matches by identity
    • sameClasses

      public static boolean sameClasses(Class[] params, Object arg1, Object arg2, Object arg3, Object arg4)
      Tests a four-argument call. params must have length four, and each class must be identical to the class of the argument in that position. A null argument matches a null parameter class, and a Wrapper is represented by Wrapper.getType().
      Parameters:
      params - the parameter classes; the length must be four
      arg1 - the first argument, or null
      arg2 - the second argument, or null
      arg3 - the third argument, or null
      arg4 - the fourth argument, or null
      Returns:
      true when the length is four and every class matches by identity
    • sameClass

      public static boolean sameClass(Class[] params, Object arg)
      Compares params[0] with the class of arg. The length of params is ignored; index zero is the slot that is read. A null argument matches a null slot, and a Wrapper is represented by Wrapper.getType().
      Parameters:
      params - the parameter classes; index zero is read
      arg - the argument to compare, or null
      Returns:
      true when the first parameter class is identical to the class of arg
    • castArgumentsToClassArray

      public static Class[] castArgumentsToClassArray(Object[] arguments)
      Parameters:
      arguments - an array of classes, values, or nulls
    • unwrap

      public static void unwrap(Object[] arguments)
      Replaces each Wrapper in arguments with Wrapper.unwrap(). Slots that are not wrappers are left as they are. The array is updated in place.
      Parameters:
      arguments - the argument array to edit
    • normalizeBoxedReturn

      public static Object normalizeBoxedReturn(Object value, Class<?> returnType)
      Re-normalizes a reflectively boxed primitive return value through the valueOf caches. Method.invoke(java.lang.Object, java.lang.Object...) boxes primitive returns with fresh instances, unlike MethodHandle-based and generated-bytecode invocation, which box through the caches; without normalization, reference identity (===) of primitive returns would differ between dispatch paths (GROOVY-12140).
      Parameters:
      value - the reflectively boxed return value (may be null)
      returnType - the declared return type of the invoked method
      Returns:
      the cache-normalized value
      Since:
      6.0.0
    • doSetMetaClass

      public static void doSetMetaClass(Object self, MetaClass mc)
      Sets the metaclass for an object, by delegating to the appropriate DefaultGroovyMethods helper method. This method was introduced as a breaking change in 2.0 to solve rare cases of stack overflow. See GROOVY-5285.

      The method is named doSetMetaClass in order to prevent misuses. Do not use this method directly unless you know what you do.

      Parameters:
      self - the object for which to set the metaclass
      mc - the metaclass
    • convertPropertyName

      public static String convertPropertyName(String prop)
      Converts a String into a standard property name.
      Parameters:
      prop - the original name
      Returns:
      the converted name