public class MetaClassHelper
extends Object
Helpers for choosing a meta-method and for the argument-distance used by that choice.
| Modifiers | Name | Description |
|---|---|---|
static Object[] |
ARRAY_WITH_NULL |
|
static Object[] |
EMPTY_ARRAY |
Shared zero-length array for a call that passes no arguments. |
static Class[] |
EMPTY_CLASS_ARRAY |
Shared zero-length class array, the same instance as EMPTY_TYPE_ARRAY. |
static Class[] |
EMPTY_TYPE_ARRAY |
Shared zero-length class array for a signature with no parameters. |
| Type Params | Return Type | Name and description |
|---|---|---|
|
public static boolean |
accessibleToConstructor(Class at, Constructor constructor)Tests whether at can access constructor under the visibility
rules applied here.
|
|
public static Object |
asPrimitiveArray(List list, Class parameterType)
|
|
public static Object[] |
asWrapperArray(Object parameters, Class componentType)Boxes a primitive array into a new Object array. |
|
public static long |
calculateParameterDistance(Class[] arguments, ParameterTypes pt)Scores how far arguments are from the parameters of pt.
|
|
public static String |
capitalize(String property)
|
|
public static Class[] |
castArgumentsToClassArray(Object[] arguments)
|
|
public static Object |
chooseEmptyMethodParams(FastArray methods)
|
|
public static Object |
chooseMostGeneralMethodWith1NullParam(FastArray methods)Warning: this method does not choose properly if multiple methods with the same distance are encountered |
|
public static boolean |
containsMatchingMethod(List list, MetaMethod method)
|
|
public static String |
convertPropertyName(String prop)Converts a String into a standard property name. |
|
public static Class[] |
convertToTypeArray(Object[] arguments)Converts array of values (incl. |
|
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. |
|
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.
|
|
public static void |
doSetMetaClass(Object self, MetaClass mc)Sets the metaclass for an object, by delegating to the appropriate DefaultGroovyMethods helper method. |
<M> |
public static 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. |
|
protected static String |
getClassName(Object object)Returns the binary name associated with object.
|
|
public static Closure |
getMethodPointer(Object object, String methodName)Returns a callable object for the given method name on the object. |
|
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.
|
|
protected static boolean |
isSuperclass(Class clazz, Class superclass)Walks clazz and then each superclass, looking for superclass.
|
|
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. |
|
public static Object |
makeArray(Object obj, Class secondary, int length)Allocates an array of the given length. |
|
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.
|
|
public static Object |
normalizeBoxedReturn(Object value, Class<?> returnType)Re-normalizes a reflectively boxed primitive return value through the valueOf caches. |
|
protected static String |
normalizedValue(Object argument)Renders one argument for logMethodCall(Object, String, Object[]). |
|
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). |
|
public static boolean |
sameClass(Class[] params, Object arg)Compares params[0] with the class of arg.
|
|
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. |
|
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. |
|
public static boolean |
sameClasses(Class[] params)Tests a call that passed no arguments against params.
|
|
public static boolean |
sameClasses(Class[] params, Object arg1)Tests a one-argument call. |
|
public static boolean |
sameClasses(Class[] params, Object arg1, Object arg2)Tests a two-argument call. |
|
public static boolean |
sameClasses(Class[] params, Object arg1, Object arg2, Object arg3)Tests a three-argument call. |
|
public static boolean |
sameClasses(Class[] params, Object arg1, Object arg2, Object arg3, Object arg4)Tests a four-argument call. |
|
protected static String |
shortName(Object object)Returns a simple name of object for a log line.
|
|
public static void |
unwrap(Object[] arguments)Replaces each Wrapper in arguments with
Wrapper.unwrap. |
|
public static Class[] |
wrap(Class[] classes)Copies classes, boxing selected primitives and rewriting
GString types to String. |
Shared zero-length array for a call that passes no arguments.
Shared zero-length class array, the same instance as EMPTY_TYPE_ARRAY.
Shared zero-length class array for a signature with no parameters.
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.
at - the class attempting the accessconstructor - the constructor being accessedtrue when the visibility rule for the constructor's modifiers accepts at
list - the original listparameterType - the resulting array type 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 - a primitive array of component type componentTypecomponentType - the primitive component type of parametersnull when componentType is not one of those eight primitives 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.
arguments - classes of the call arguments, in order; a null entry is a null argumentpt - the candidate parameter list
arguments - an array of classes, values, or nulls
methods - the methods to choose fromWarning: this method does not choose properly if multiple methods with the same distance are encountered
methods - the methods to choose from
list - a list of MetaMethodsmethod - the MetaMethod of interestConverts a String into a standard property name.
prop - the original name Converts array of values (incl. null) to their respective types.
arguments - the arguments 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.
init - text that opens the messagemethod - the meta-method that failedobject - the receiver the method was invoked onargs - the arguments passed to the methodreason - the failure to reportsetReason - whether reason is attached as the cause 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.
methodOrList - the overload set, as a FastArray of ParameterTypes;
any other value makes this method return falsetypes - argument classes passed to ParameterTypes.isValidMethod;
null makes this method return falsearguments - 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 falsetrue 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 parametersSets 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.
self - the object for which to set the metaclassmc - the metaclassDrops 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.
M - the candidate type. Each element is read as ParameterTypescandidates - the overload candidates to filterarguments - 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 withcandidates
itself when none of them fit 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.
object - a class, an instance, or nullobject is nullReturns 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.
object - the object containing the methodmethodName - the method of interest Tests whether a value of classToTransformFrom may be passed where
classToTransformTo is expected, including Groovy coercions beyond
Class.isAssignableFrom.
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:
classToTransformTo - the destination typeclassToTransformFrom - the source type, or nulltrue when the source may be used as the destination 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.
clazz - the class whose superclass chain is examined, or nullsuperclass - the class to find on that chaintrue when superclass is clazz or a superclass of it 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.
object - the receiver, used in the logger namemethodName - the method that was invokedarguments - the arguments, or null when there are none to render 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.
obj - instance whose class supplies the component type, or nullsecondary - component type used when obj is nulllength - the requested array length 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 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.
arguments - the source values; elements before offset are ignoredoffset - the first index copied into the resultfallback - component type of an all-null range, and the interface tried when the common class is Object Re-normalizes a reflectively boxed primitive return value through the
valueOf caches. Method.invoke 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).
value - the reflectively boxed return value (may be null)returnType - the declared return type of the invoked method 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.
argument - the value to render, or nullTests 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.
arguments - the runtime argument classesparameters - the formal parameter classestrue when the lengths match and each argument is assignable to its parameter 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.
params - the parameter classes; index zero is readarg - the argument to compare, or nulltrue when the first parameter class is identical to the class of arg 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.
params - the parameter classes, null slots includedarguments - the call argumentsweakNullCheck - unusedtrue when the lengths match and every slot matches by identityTests 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.
params - the parameter classes, null slots includedarguments - the call argumentstrue when the lengths match and every slot matches by identity Tests a call that passed no arguments against params.
No class is compared; the result is whether the array is empty.
params - the parameter classes of the candidate signaturetrue when params has length zero 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.
params - the parameter classes; the length must be onearg1 - the sole argument, or nulltrue when the length is one and the class matches by identity 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.
params - the parameter classes; the length must be twoarg1 - the first argument, or nullarg2 - the second argument, or nulltrue when the length is two and both classes match by identity 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.
params - the parameter classes; the length must be threearg1 - the first argument, or nullarg2 - the second argument, or nullarg3 - the third argument, or nulltrue when the length is three and every class matches by identity 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.
params - the parameter classes; the length must be fourarg1 - the first argument, or nullarg2 - the second argument, or nullarg3 - the third argument, or nullarg4 - the fourth argument, or nulltrue when the length is four and every class matches by identity 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.
object - the value whose class name is shortened, or nullunknownClass, or unknownClassName Replaces each Wrapper in arguments with
Wrapper.unwrap. Slots that are not wrappers are left as they are.
The array is updated in place.
arguments - the argument array to edit 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.
classes - the classes to adapt; entries may be null