Class MetaClassHelper
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final Object[]Shared one-element array whose only slot isnull.static final Object[]Shared zero-length array for a call that passes no arguments.static final Class[]Shared zero-length class array, the same instance asEMPTY_TYPE_ARRAY.static final Class[]Shared zero-length class array for a signature with no parameters. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic booleanaccessibleToConstructor(Class at, Constructor constructor) Tests whetheratcan accessconstructorunder the visibility rules applied here.static ObjectasPrimitiveArray(List list, Class parameterType) static Object[]asWrapperArray(Object parameters, Class componentType) Boxes a primitive array into a newObjectarray.static longcalculateParameterDistance(Class[] arguments, ParameterTypes pt) Scores how farargumentsare from the parameters ofpt.static Stringcapitalize(String property) Deprecated, for removal: This API element is subject to removal in a future version.static Class[]castArgumentsToClassArray(Object[] arguments) static ObjectchooseEmptyMethodParams(FastArray methods) static ObjectDeprecated.static booleancontainsMatchingMethod(List list, MetaMethod method) static StringconvertPropertyName(String prop) Converts a String into a standard property name.static Class[]convertToTypeArray(Object[] arguments) Converts array of values (incl.static GroovyRuntimeExceptioncreateExceptionText(String init, MetaMethod method, Object object, Object[] args, Throwable reason, boolean setReason) Builds aGroovyRuntimeExceptiondescribing a failed meta-method call.static booleandependsOnMethodClosureArity(Object methodOrList, Class[] types, Object[] arguments) Tells whether choosing amongmethodOrListfor 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.static voiddoSetMetaClass(Object self, MetaClass mc) Sets the metaclass for an object, by delegating to the appropriateDefaultGroovyMethodshelper method.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.protected static StringgetClassName(Object object) Returns the binary name associated withobject.static ClosuregetMethodPointer(Object object, String methodName) Returns a callable object for the given method name on the object.static booleanisAssignableFrom(Class classToTransformTo, Class classToTransformFrom) Tests whether a value ofclassToTransformFrommay be passed whereclassToTransformTois expected, including Groovy coercions beyondClass.isAssignableFrom(Class).protected static booleanisSuperclass(Class clazz, Class superclass) Walksclazzand then each superclass, looking forsuperclass.static voidlogMethodCall(Object object, String methodName, Object[] arguments) Logs an invocation atLevel.FINERwhen that level is enabled for the call's logger.static ObjectAllocates an array of the givenlength.static ObjectmakeCommonArray(Object[] arguments, int offset, Class fallback) Copiesargumentsfromoffsetto the end into a new array whose component type is shared by that range.static ObjectnormalizeBoxedReturn(Object value, Class<?> returnType) Re-normalizes a reflectively boxed primitive return value through thevalueOfcaches.protected static StringnormalizedValue(Object argument) Renders one argument forlogMethodCall(Object, String, Object[]).static booleanparametersAreCompatible(Class[] arguments, Class[] parameters) Tests whether each argument class is acceptable for the parameter class in the same position, usingisAssignableFrom(Class, Class).static booleanComparesparams[0]with the class ofarg.static booleansameClasses(Class[] params) Tests a call that passed no arguments againstparams.static booleansameClasses(Class[] params, Object arg1) Tests a one-argument call.static booleansameClasses(Class[] params, Object[] arguments) Tests whether each parameter class is identical to the class derived from the argument in the same position.static booleansameClasses(Class[] params, Object[] arguments, boolean weakNullCheck) Tests whether each parameter class is identical to the class derived from the argument in the same position.static booleansameClasses(Class[] params, Object arg1, Object arg2) Tests a two-argument call.static booleansameClasses(Class[] params, Object arg1, Object arg2, Object arg3) Tests a three-argument call.static booleanTests a four-argument call.protected static StringReturns a simple name ofobjectfor a log line.static voidstatic Class[]
-
Field Details
-
EMPTY_ARRAY
Shared zero-length array for a call that passes no arguments. -
EMPTY_TYPE_ARRAY
Shared zero-length class array for a signature with no parameters. -
EMPTY_CLASS_ARRAY
Shared zero-length class array, the same instance asEMPTY_TYPE_ARRAY. -
ARRAY_WITH_NULL
Shared one-element array whose only slot isnull. 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
Tests whetheratcan accessconstructorunder the visibility rules applied here. A public constructor is accessible. A private constructor is accessible when the binary name ofatequalsConstructor.getName(), which is the binary name of the declaring class. A protected constructor is accessible whenatand 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 isator a superclass ofat. 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 accessconstructor- the constructor being accessed- Returns:
truewhen the visibility rule for the constructor's modifiers acceptsat
-
asWrapperArray
Boxes a primitive array into a newObjectarray.parametersis cast to the primitive array named bycomponentType, and each element is boxed. The component types handled areboolean,char,byte,short,int,long,float, anddouble. Any other component type,nullincluded, producesnulland leavesparametersunread.- Parameters:
parameters- a primitive array of component typecomponentTypecomponentType- the primitive component type ofparameters- Returns:
- a new array of boxed elements, or
nullwhencomponentTypeis not one of those eight primitives
-
asPrimitiveArray
- Parameters:
list- the original listparameterType- the resulting array type- Returns:
- the constructed array
-
dependsOnMethodClosureArity
public static boolean dependsOnMethodClosureArity(Object methodOrList, Class[] types, Object[] arguments) Tells whether choosing amongmethodOrListfor 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 aFastArrayofParameterTypes; any other value makes this method returnfalsetypes- argument classes passed toParameterTypes.isValidMethod(Class[]);nullmakes this method returnfalsearguments- the call arguments. AMethodClosureis compared with the SAM arity of the functional-interface parameter at the same index.nullmakes this method returnfalse- Returns:
truewhen two candidates that are still valid fortypesaccept a method closure at the same position through functional interfaces whose abstract methods take different numbers of parameters- Since:
- 6.0.1
-
filterByMethodClosureArity
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 asParameterTypes- Parameters:
candidates- the overload candidates to filterarguments- the call arguments. A candidate is kept only when the functional-interface parameter at the index of eachMethodClosurehas an abstract method the closure can be called with- Returns:
- the candidates that accept those method closures, or
candidatesitself when none of them fit - Since:
- 6.0.1
-
calculateParameterDistance
Scores how farargumentsare from the parameters ofpt. 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 scores0.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 toGeneratedClosurepassed toClosure. An interface parameter scores the longest path through superclasses and superinterfaces, and scores a negative value when no such path exists. AClosurethat does not implement the interface is scored as an object instead, with a lower score when itsdoCallcount matches the single abstract method. A class that declares more than onedoCallmatches 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, andObject) 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 whenGStringis passed toString. A null argument scores0forNullObjectand1forObject; otherwise the score is the distance from the parameter up toObject. 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 argumentpt- the candidate parameter list- Returns:
- the packed distance; a smaller non-negative value is a closer fit
-
capitalize
Deprecated, for removal: This API element is subject to removal in a future version.UseBeanUtils.capitalize(java.lang.String)instead -
chooseEmptyMethodParams
- 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.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
- Parameters:
list- a list of MetaMethodsmethod- the MetaMethod of interest- Returns:
- true if a method of the same matching prototype was found in the list
-
convertToTypeArray
Converts array of values (incl.null) to their respective types.- Parameters:
arguments- the arguments- Returns:
- the types of the arguments
-
makeCommonArray
Copiesargumentsfromoffsetto 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 towardObjectuntilClass.isAssignableFrom(Class)accepts every later non-null element. A range of only nulls usesfallback. When the chosen class isObjectandfallbackis an interface, the interface is used instead when every slot in the range is non-null and, for each element,fallbackis a direct interface of that element's class or of a superclass belowObject.- Parameters:
arguments- the source values; elements beforeoffsetare ignoredoffset- the first index copied into the resultfallback- component type of an all-null range, and the interface tried when the common class isObject- Returns:
- the array of the chosen component type holding the copied elements
-
makeArray
Allocates an array of the givenlength. The component type is the runtime class ofobjwhenobjis non-null, andsecondarywhen it is null. The new array is empty;objis not stored in it.- Parameters:
obj- instance whose class supplies the component type, ornullsecondary- component type used whenobjis nulllength- 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 aGroovyRuntimeExceptiondescribing a failed meta-method call. The message isinit, themethod," on: ", the receiverobject," with arguments: ",FormatHelper.toString(args)," reason: ", andreason, concatenated in that order. WhensetReasonis true,reasonis 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 messagemethod- the meta-method that failedobject- the receiver the method was invoked onargs- the arguments passed to the methodreason- the failure to reportsetReason- whetherreasonis attached as the cause- Returns:
- the populated exception
-
getClassName
Returns the binary name associated withobject. A null argument returns null. AClasscontributes its own name, rather than the namejava.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
objectis null
-
getMethodPointer
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 methodmethodName- the method of interest- Returns:
- the resulting closure-like method pointer
-
isAssignableFrom
Tests whether a value ofclassToTransformFrommay be passed whereclassToTransformTois expected, including Groovy coercions beyondClass.isAssignableFrom(Class). A null source is accepted for every target, and a target ofObjectaccepts every source. Both classes are boxed before the remaining checks, so a primitive and its wrapper match.booleanandchartake part through boxing and ordinary assignability. The further coercions are:Integeralso acceptsShort,Byte, andBigInteger.Longalso acceptsInteger,Short, andByte.Floatalso acceptsInteger,Long,Short, andByte.Doublealso acceptsInteger,Long,Short,Byte,Float,BigDecimal, andBigInteger.BigIntegeralso acceptsInteger,Long,Short, andByte.BigDecimalalso acceptsDouble,Float,BigInteger,Integer,Long,Short, andByte.Shortalso acceptsByte.Stringalso acceptsGStringand its subclasses.
Class.isAssignableFrom(Class)on the boxed classes.- Parameters:
classToTransformTo- the destination typeclassToTransformFrom- the source type, or null- Returns:
truewhen the source may be used as the destination
-
isSuperclass
Walksclazzand then each superclass, looking forsuperclass. The walk includesclazzitself, so a class counts as a superclass of itself here. A nullclazzends the walk immediately.- Parameters:
clazz- the class whose superclass chain is examined, or nullsuperclass- the class to find on that chain- Returns:
truewhensuperclassisclazzor a superclass of it
-
parametersAreCompatible
Tests whether each argument class is acceptable for the parameter class in the same position, usingisAssignableFrom(Class, Class). The arrays must have the same length; a shorter or longer argument list is incompatible, varargs included.- Parameters:
arguments- the runtime argument classesparameters- the formal parameter classes- Returns:
truewhen the lengths match and each argument is assignable to its parameter
-
logMethodCall
Logs an invocation atLevel.FINERwhen that level is enabled for the call's logger. The logger name ismethodCalls.followed bygetClassName(Object)ofobjectandmethodName; a null receiver is concatenated as the textnull. The log record's source method ismethodNameplus the arguments rendered bynormalizedValue(Object), separated by commas. A nullargumentsarray produces an empty pair of parentheses. The log message iscalled from MetaClass.invokeMethod. A logger that is not atLevel.FINERreturns before the message is built.- Parameters:
object- the receiver, used in the logger namemethodName- the method that was invokedarguments- the arguments, or null when there are none to render
-
normalizedValue
Renders one argument forlogMethodCall(Object, String, Object[]). The text isObject.toString(). When that text is longer than twelve characters, the first ten are kept and..is appended. AStringis then wrapped in single quotes. WhentoStringthrows, the result isshortName(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
Returns a simple name ofobjectfor a log line. A null argument, or an argument whose class is null, yieldsunknownClass. Otherwise the binary name fromgetClassName(Object)is used: aClasscontributes 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 yieldsunknownClassName.- Parameters:
object- the value whose class name is shortened, or null- Returns:
- the simple name,
unknownClass, orunknownClassName
-
wrap
Copiesclasses, boxing selected primitives and rewritingGStringtypes toString. A null entry stays null.int,byte,long,double, andfloatbecome the matching wrapper class.boolean,char,short, andvoidstay primitive. A type that isGStringor a subclass of it becomesString. 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
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. AWrapperis represented byWrapper.getType(), and every other argument byObject.getClass().weakNullCheckis not consulted; null and non-null arguments share this comparison.- Parameters:
params- the parameter classes, null slots includedarguments- the call argumentsweakNullCheck- unused- Returns:
truewhen the lengths match and every slot matches by identity
-
sameClasses
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. AWrapperis represented byWrapper.getType(), and every other argument byObject.getClass().- Parameters:
params- the parameter classes, null slots includedarguments- the call arguments- Returns:
truewhen the lengths match and every slot matches by identity
-
sameClasses
Tests a call that passed no arguments againstparams. No class is compared; the result is whether the array is empty.- Parameters:
params- the parameter classes of the candidate signature- Returns:
truewhenparamshas length zero
-
sameClasses
Tests a one-argument call.paramsmust have length one, and its only class must be identical to the class ofarg1. A null argument matches a null parameter class, and aWrapperis represented byWrapper.getType().- Parameters:
params- the parameter classes; the length must be onearg1- the sole argument, or null- Returns:
truewhen the length is one and the class matches by identity
-
sameClasses
Tests a two-argument call.paramsmust 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 aWrapperis represented byWrapper.getType().- Parameters:
params- the parameter classes; the length must be twoarg1- the first argument, or nullarg2- the second argument, or null- Returns:
truewhen the length is two and both classes match by identity
-
sameClasses
Tests a three-argument call.paramsmust 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 aWrapperis represented byWrapper.getType().- Parameters:
params- the parameter classes; the length must be threearg1- the first argument, or nullarg2- the second argument, or nullarg3- the third argument, or null- Returns:
truewhen 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.paramsmust 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 aWrapperis represented byWrapper.getType().- Parameters:
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 null- Returns:
truewhen the length is four and every class matches by identity
-
sameClass
Comparesparams[0]with the class ofarg. The length ofparamsis ignored; index zero is the slot that is read. A null argument matches a null slot, and aWrapperis represented byWrapper.getType().- Parameters:
params- the parameter classes; index zero is readarg- the argument to compare, or null- Returns:
truewhen the first parameter class is identical to the class ofarg
-
castArgumentsToClassArray
- Parameters:
arguments- an array of classes, values, or nulls
-
unwrap
Replaces eachWrapperinargumentswithWrapper.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
Re-normalizes a reflectively boxed primitive return value through thevalueOfcaches.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 benull)returnType- the declared return type of the invoked method- Returns:
- the cache-normalized value
- Since:
- 6.0.0
-
doSetMetaClass
Sets the metaclass for an object, by delegating to the appropriateDefaultGroovyMethodshelper 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 metaclassmc- the metaclass
-
convertPropertyName
Converts a String into a standard property name.- Parameters:
prop- the original name- Returns:
- the converted name
-
BeanUtils.capitalize(java.lang.String)instead