Class ClassNode
- All Implemented Interfaces:
GroovydocHolder<AnnotatedNode>,NodeMetaDataHandler
- Direct Known Subclasses:
DecompiledClassNode,InnerClassNode,MixinNode,WideningCategories.LowestUpperBoundClassNode
A ClassNode should be created using the methods in ClassHelper. This ClassNode may be used to represent a class declaration or any other type. This class uses a proxy mechanism allowing to create a class for a plain name at AST creation time. In another phase of the compiler the real ClassNode for the plain name may be found. To avoid the need of exchanging this ClassNode with an instance of the correct ClassNode the correct ClassNode is set as redirect. Most method calls are then redirected to that ClassNode.
There are three types of ClassNodes:
- Primary ClassNodes:
A primary ClassNode is one where we have a source representation which is to be compiled by Groovy and which we have an AST for. The groovy compiler will output one class for each such ClassNode that passes through AsmBytecodeGenerator... not more, not less. That means for example Closures become such ClassNodes too at some point. - ClassNodes create through different sources (typically created
from a java.lang.reflect.Class object):
The compiler will not output classes from these, the methods usually do not contain bodies. These kind of ClassNodes will be used in different checks, but not checks that work on the method bodies. For example if such a ClassNode is a super class to a primary ClassNode, then the abstract method test and others will be done with data based on these. Theoretically it is also possible to mix both (1 and 2) kind of classes in a hierarchy, but this probably works only in the newest Groovy versions. Such ClassNodes normally have to isResolved() returning true without having a redirect.In the Groovy compiler the only version of this, that exists, is a ClassNode created through a Class instance - Labels:
ClassNodes created through ClassHelper.makeWithoutCaching. They are placeholders, its redirect points to the real structure, which can be a label too, but following all redirects it should end with a ClassNode from one of the other two categories. If ResolveVisitor finds such a node, it tries to set the redirects. Any such label created after ResolveVisitor has done its work needs to have a redirect pointing to case 1 or 2. If not the compiler may react strange... this can be considered as a kind of dangling pointer.
To describe generic type signature see getGenericsTypes() and
setGenericsTypes(GenericsType[]). These methods are not proxied,
they describe the type signature used at the point of declaration or the
type signatures provided by the class. If the type signatures provided
by the class are needed, then a call to redirect() will help.
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected Class<?>static final ClassNode[]protected booleanprotected final Objectstatic final ClassNodestatic final ClassNodeFields inherited from interface groovy.lang.groovydoc.GroovydocHolder
DOC_COMMENT -
Constructor Summary
ConstructorsConstructorDescriptionConstructs a non-primaryClassNodefrom a real Java class.Constructs a primaryClassNoderepresenting a class declaration with superclass.ClassNode(String name, int modifiers, ClassNode superClass, ClassNode[] interfaces, MixinNode[] mixins) Constructs a primaryClassNoderepresenting a class declaration with all components. -
Method Summary
Modifier and TypeMethodDescriptionaddConstructor(int modifiers, Parameter[] parameters, ClassNode[] exceptions, Statement code) voidaddField(String name, int modifiers, ClassNode type, Expression initialValue) Creates and adds aFieldNodeto this ClassNode with the specified properties.voidAdds aFieldNodeto this ClassNode.addFieldFirst(String name, int modifiers, ClassNode type, Expression initialValue) Creates and adds aFieldNodeto the beginning of this ClassNode's field list with the specified properties.voidaddFieldFirst(FieldNode node) Adds aFieldNodeto this ClassNode at the beginning of the field list.voidaddInterface(ClassNode node) Adds an interface to the list of interfaces implemented by thisClassNode.addMethod(String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) Creates and adds aMethodNodeto this ClassNode with the specified properties, but only if a method with the same name and parameter signature does not already exist.voidaddMethod(MethodNode node) Adds aMethodNodeto this ClassNode.voidvoidaddObjectInitializerStatements(Statement statement) Adds a statement to the object initializer.addProperty(String name, int modifiers, ClassNode type, Expression initialValue, Statement getterBlock, Statement setterBlock) Creates and adds aPropertyNodeto this ClassNode with the specified properties, or returns an existing property with the same name if one is already present.voidaddProperty(PropertyNode node) Adds aPropertyNodeto this ClassNode.voidaddStaticInitializerStatements(List<Statement> statements, boolean fieldInit) addSyntheticMethod(String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) Adds a synthetic method as part of the compilation process.voidaddTransform(Class<? extends ASTTransformation> transform, ASTNode node) voidaddTypeAnnotation(AnnotationNode annotation) voidaddTypeAnnotations(List<AnnotationNode> annotations) booleandeclaresAnyInterfaces(ClassNode... classNodes) booleandeclaresInterface(ClassNode classNode) booleanCompares thisClassNodewith another object for equality.Returns a list of all abstractMethodNodes declared in this ClassNode.Returns all declaredMethodNodes from this ClassNode and its superclasses and interfaces as a list.Returns all annotations attached to this AST node.getAnnotations(ClassNode type) Returns annotations of a specific type attached to this AST node.Returns the component type of this array ClassNode.getDeclaredConstructor(Parameter[] parameters) getDeclaredField(String name) Finds aFieldNodematching the given name declared directly in this class.getDeclaredMethod(String name, Parameter[] parameters) Finds aMethodNodematching the given name and parameter signature declared directly in this class.getDeclaredMethods(String name) Returns a list of allMethodNodes with the given name declared directly in this class.Returns all declaredMethodNodes from this ClassNode and its superclasses and interfaces.Returns the enclosingMethodNodeof this local inner class, ornullif this is not a local inner class.Finds aFieldNodematching the given name in this class or any of its superclasses.Deprecated, for removal: This API element is subject to removal in a future version.Returns allFieldNodes declared in this ClassNode, including inherited fields.Returns the generic type parameters for thisClassNode, ornullif none are defined.getGetterMethod(String getterName) Finds a getterMethodNodematching the given name, optionally searching superclasses.getGetterMethod(String getterName, boolean searchSupers) Finds a getterMethodNodematching the given name, optionally searching superclasses and interfaces.Returns an iterator over the inner classes defined within thisClassNode.Finds aMethodNodematching the given name and parameter signature in this class or any of its superclasses.Returns allMethodNodes declared in this ClassNode, including inherited and synthetic methods.getMethods(String name) Returns a list of allMethodNodes with the given name from this class and its superclasses.intReturns the modifier flags for thisClassNode, combining visibility and behavioral modifiers.getName()Returns the fully-qualified name of this class after following any redirects.Returns the outer class of thisClassNode, ornullif this is not an inner class.Returns a list of all outer classes enclosing thisClassNodein hierarchical order.getOuterField(String name) getPlainNodeReference(boolean skipPrimitives) Returns allPropertyNodes declared in this ClassNode.getProperty(String name) Finds aPropertyNodematching the given name in this ClassNode.Gets the record components of record type.getSetterMethod(String setterName) Finds a setterMethodNodematching the given name, optionally searching superclasses.getSetterMethod(String setterName, boolean voidOnly) Finds a setterMethodNodematching the given name.getText()Returns a human-readable text representation of this AST node.Map<Class<? extends ASTTransformation>,Set<ASTNode>> getTransforms(CompilePhase phase) getTypeAnnotations(ClassNode type) Returns the concrete class this classnode relates to.Returns the unresolved interfaces implemented by thisClassNode, using redirect resolution by default.getUnresolvedInterfaces(boolean deref) Returns the unresolved interfaces implemented by thisClassNodewith optional redirect resolution.Returns the unresolved super class of thisClassNode, using redirect resolution by default.getUnresolvedSuperClass(boolean deref) Returns the unresolved super class of thisClassNodewith optional redirect resolution.booleanhasDeclaredMethod(String name, Parameter[] parameters) Tests whether a method with the given name and parameter signature is declared directly in this class (not inherited from a superclass).inthashCode()Returns the hash code for thisClassNode.booleanTests whether a method with the given name and parameter signature exists in this class or any of its superclasses.booleanbooleanhasPossibleMethod(String name, Expression arguments) Determines if the type has a possibly-matching instance method with the given name and arguments.booleanhasPossibleStaticMethod(String name, Expression arguments) Checks if the given method has a possibly matching static method with the given name and arguments.booleanhasProperty(String name) Tests whether a property with the given name exists in this ClassNode.booleanimplementsAnyInterfaces(ClassNode... classNodes) booleanimplementsInterface(ClassNode classNode) booleanReturns whether thisClassNoderepresents an abstract class.booleanReturns whether thisClassNodehas been marked as annotated.booleanReturns whether thisClassNoderepresents an annotation type (annotation definition).booleanisArray()Determines whether this ClassNode represents an array type.booleanisDerivedFrom(ClassNode type) booleanReturns whether thisClassNoderepresents a type that implements theGroovyObjectinterface.booleanisEnum()Returns whether thisClassNoderepresents an enumeration type.booleanbooleanReturns whether thisClassNoderepresents an interface type.booleanDetermines whether this ClassNode is a primary node or redirects to one.booleanisRecord()Checks if theClassNodeinstance represents a nativerecord.booleanReturns whether thisClassNodeis a redirect (proxy) node for another ClassNode.booleanDetermines whether this ClassNode has been resolved to an actual Java class.booleanisScript()Returns whether thisClassNoderepresents a Groovy script body.booleanReturns whether this inner class or closure was declared inside a script body.booleanisSealed()booleanReturns whether this inner class or closure was declared inside a static method context.booleanIndicates that this class has been "promoted" to public by Groovy when in fact there was no public modifier explicitly in the source code.booleanReturns aClassNoderepresenting an array of the type represented by this.protected booleanparametersEqual(Parameter[] a, Parameter[] b) Deprecated, for removal: This API element is subject to removal in a future version.voidpositionStmtsAfterEnumInitStmts(List<Statement> staticFieldInitializerStatements) redirect()Returns theClassNodethis node is a proxy for or the node itself.voidvoidremoveField(String oldName) Removes theFieldNodewith the given name from this ClassNode.voidremoveMethod(MethodNode node) Removes the givenMethodNodefrom this ClassNode.voidrenameField(String oldName, String newName) voidsetAnnotated(boolean annotated) Marks thisClassNodeas having annotations attached to it.protected voidDeprecated, for removal: This API element is subject to removal in a future version.voidsetEnclosingMethod(MethodNode enclosingMethod) Sets the enclosingMethodNodefor this local inner class.voidsetGenericsPlaceHolder(boolean placeholder) voidsetGenericsTypes(GenericsType[] genericsTypes) Sets the generic type parameters for thisClassNode.voidsetInterfaces(ClassNode[] interfaces) Sets the interfaces implemented by thisClassNode.voidvoidsetModifiers(int modifiers) Sets the modifier flags for thisClassNode.voidsetModule(ModuleNode module) Sets the fully-qualified name of this class, delegating to the redirect if one exists.voidsetPermittedSubclasses(List<ClassNode> permittedSubclasses) voidsetRecordComponents(List<RecordComponentNode> recordComponents) Sets the record components for record type.voidsetRedirect(ClassNode node) Sets this instance as a proxy for the givenClassNode, enabling deferred class resolution.voidsetScript(boolean script) Marks thisClassNodeas a script or removes the script flag.voidsetScriptBody(boolean scriptBody) Marks this inner class or closure as being declared inside a script body.voidsetStaticClass(boolean staticClass) Marks this inner class or closure as being declared in a static method context.voidsetSuperClass(ClassNode superClass) Sets the super class of thisClassNode.voidsetSyntheticPublic(boolean syntheticPublic) Marks thisClassNodeas having synthetic public visibility.voidsetUnresolvedSuperClass(ClassNode superClass) Sets the unresolved super class for thisClassNode.voidsetUsingGenerics(boolean usesGenerics) toString()Returns a string representation of this ClassNode for debugging and display purposes.toString(boolean showRedirect) Returns a string representation of this ClassNode with optional redirect information.tryFindPossibleMethod(String name, Expression arguments) voidvisitContents(GroovyClassVisitor visitor) Methods inherited from class org.codehaus.groovy.ast.AnnotatedNode
addAnnotation, addAnnotation, addAnnotations, getDeclaringClass, getGroovydoc, getInstance, hasNoRealSourcePosition, isSynthetic, setDeclaringClass, setHasNoRealSourcePosition, setSyntheticMethods inherited from class org.codehaus.groovy.ast.ASTNode
copyNodeMetaData, getColumnNumber, getLastColumnNumber, getLastLineNumber, getLineNumber, getMetaDataMap, setColumnNumber, setLastColumnNumber, setLastLineNumber, setLineNumber, setMetaDataMap, setSourcePosition, visitMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, waitMethods inherited from interface org.codehaus.groovy.ast.NodeMetaDataHandler
copyNodeMetaData, getNodeMetaData, getNodeMetaData, getNodeMetaData, newMetaDataMap, putNodeMetaData, removeNodeMetaData, setNodeMetaData
-
Field Details
-
EMPTY_ARRAY
-
THIS
-
SUPER
-
isPrimaryNode
protected boolean isPrimaryNode -
lazyInitLock
-
clazz
-
-
Constructor Details
-
ClassNode
public ClassNode(String name, int modifiers, ClassNode superClass, ClassNode[] interfaces, MixinNode[] mixins) Constructs a primaryClassNoderepresenting a class declaration with all components. This constructor creates a new ClassNode that will be compiled by Groovy. The node represents an actual source class definition with specified interfaces and mixins.- Parameters:
name- the fully-qualified name of the class (e.g., "com.example.MyClass")modifiers- the bytecode modifiers (flags fromModifierorOpcodes)superClass- the base class (ClassNoderepresenting the parent type); useClassHelper.OBJECT_TYPEif no direct base classinterfaces- array ofClassNodeinstances for interfaces implemented by this class; may be emptymixins- array ofMixinNodeinstances to be mixed into this class; may be empty
-
ClassNode
Constructs a primaryClassNoderepresenting a class declaration with superclass. This is a convenience constructor for creating classes with a single superclass and no interfaces or mixins. It delegates to the full constructor with empty interface and mixin arrays.- Parameters:
name- the fully-qualified name of the class (e.g., "com.example.MyClass")modifiers- the bytecode modifiers (flags fromModifierorOpcodes)superClass- the base class (ClassNoderepresenting the parent type); useClassHelper.OBJECT_TYPEif no direct base class
-
ClassNode
Constructs a non-primaryClassNodefrom a real Java class. This constructor creates a ClassNode that represents an actual Java class loaded at runtime (not a Groovy source class). The class information is lazily initialized from reflection, and the node will not be compiled by Groovy.- Parameters:
c- the Java class (Class) to wrap; must not benull
-
-
Method Details
-
redirect
Returns theClassNodethis node is a proxy for or the node itself. If this ClassNode has been set as a proxy to another ClassNode viasetRedirect(ClassNode), recursively follows the redirect chain to return the ultimate target ClassNode. If no redirect is set, returnsthis. This mechanism allows lazy resolution of class references during compilation.- Returns:
- the final
ClassNodein the redirect chain; nevernull
-
isRedirectNode
public boolean isRedirectNode()Returns whether thisClassNodeis a redirect (proxy) node for another ClassNode. A redirect node acts as a placeholder that forwards most method calls to its target ClassNode. This mechanism is used during compilation to defer class resolution until the actual target class is available. The actual target can be found usingredirect().- Returns:
trueif this node redirects to another ClassNode;falseif it is a standalone node- See Also:
-
setRedirect
Sets this instance as a proxy for the givenClassNode, enabling deferred class resolution. After calling this method, most operations on this ClassNode are forwarded to the target ClassNode. Redirect is only allowed for non-primary ClassNodes (seeisPrimaryClassNode()). If the target isnull, the redirect is removed, making this node standalone again.- Parameters:
node- theClassNodeto redirect to; ifnullthe redirect is cleared- Throws:
GroovyBugError- if this is a primary ClassNode, as redirects are only for proxy nodes
-
isPrimaryClassNode
public boolean isPrimaryClassNode()Determines whether this ClassNode is a primary node or redirects to one. A primary ClassNode represents actual Groovy source code that will be compiled into bytecode. Returnstrueif this node is primary or if its redirect target (or array component type) is a primary ClassNode. Non-primary nodes are typically loaded via reflection.- Returns:
trueif this is a primary ClassNode or redirects to one;falseif it only represents a reflected class
-
getPlainNodeReference
-
getPlainNodeReference
-
getModule
-
setModule
-
getCompileUnit
-
setCompileUnit
Deprecated, for removal: This API element is subject to removal in a future version. -
getPackage
-
getPackageName
-
hasPackageName
public boolean hasPackageName() -
getNameWithoutPackage
-
getUnresolvedName
-
getUnresolvedSuperClass
Returns the unresolved super class of thisClassNode, using redirect resolution by default. The unresolved super class represents the raw class hierarchy without applying redirect resolution. Returnsnullif this class has no explicit superclass.- Returns:
- the unresolved
ClassNoderepresenting the super class, ornull - See Also:
-
getUnresolvedSuperClass
Returns the unresolved super class of thisClassNodewith optional redirect resolution. Whenderefistrue, resolves redirects recursively; otherwise returns the raw superclass stored in this ClassNode. Resolving may trigger lazy class initialization.- Parameters:
deref-trueto apply redirect resolution,falseto return raw superclass- Returns:
- the unresolved
ClassNoderepresenting the super class, ornull - See Also:
-
setUnresolvedSuperClass
Sets the unresolved super class for thisClassNode. This method sets the raw superclass without applying any redirect resolution.- Parameters:
superClass- theClassNoderepresenting the super class, ornull
-
getUnresolvedInterfaces
Returns the unresolved interfaces implemented by thisClassNode, using redirect resolution by default. The unresolved interfaces represent the raw interface hierarchy without applying redirect resolution. Returns an empty array if this class implements no interfaces.- Returns:
- an array of
ClassNoderepresenting the interfaces, nevernull - See Also:
-
getUnresolvedInterfaces
Returns the unresolved interfaces implemented by thisClassNodewith optional redirect resolution. Whenderefistrue, resolves redirects recursively; otherwise returns the raw interfaces stored in this ClassNode. Resolving may trigger lazy class initialization.- Parameters:
deref-trueto apply redirect resolution,falseto return raw interfaces- Returns:
- an array of
ClassNoderepresenting the interfaces, nevernull - See Also:
-
getText
Description copied from class:ASTNodeReturns a human-readable text representation of this AST node. Used for debugging and error messages. Default implementation returns a message indicating the representation is not yet implemented for this node type. -
getName
Returns the fully-qualified name of this class after following any redirects. If this ClassNode is a proxy for another ClassNode, the name of the target is returned. The name remains consistent across all compilation phases for the redirected type.- Returns:
- the fully-qualified class name (e.g., "com.example.MyClass" or "int[]")
-
setName
Sets the fully-qualified name of this class, delegating to the redirect if one exists. Allows the class name to be updated after construction, which is occasionally used during AST transformation phases. Changes are propagated to the redirect target if present.- Parameters:
name- the new fully-qualified class name to set- Returns:
- the name that was set
-
getModifiers
public int getModifiers()Returns the modifier flags for thisClassNode, combining visibility and behavioral modifiers. The flags are represented as a bitmask using ASM/bytecode conventions (e.g.,ACC_PUBLIC,ACC_ABSTRACT,ACC_INTERFACE,ACC_ENUM). This method follows redirects if present, ensuring the modifiers of the actual target ClassNode are returned. Individual modifiers can be tested using bitwise AND operations with the ASM Opcodes constants.- Returns:
- the modifier flags as an integer bitmask
- See Also:
-
setModifiers
public void setModifiers(int modifiers) Sets the modifier flags for thisClassNode. The modifiers are a bitmask of ASM/bytecode convention flags (e.g.,ACC_PUBLIC,ACC_ABSTRACT,ACC_INTERFACE,ACC_ENUM). Calling this method directly on a redirect node updates the redirect's modifiers instead of this node's. Use this method to control visibility and structural attributes like abstractness or finality.- Parameters:
modifiers- the new modifier flags as a bitmask- See Also:
-
getSuperClass
- Returns:
- the
ClassNodeof the super class of this type
-
setSuperClass
Sets the super class of thisClassNode. If this ClassNode has a redirect, the super class is set on the redirect instead. Updates the generics usage indicator if the super class uses generics and this is a primary ClassNode.- Parameters:
superClass- theClassNoderepresenting the super class, ornull- See Also:
-
getInterfaces
- Returns:
- the interfaces implemented by this
ClassNode
-
getAllInterfaces
-
setInterfaces
Sets the interfaces implemented by thisClassNode. If this ClassNode has a redirect, the interfaces are set on the redirect instead. Updates the generics usage indicator if any interface uses generics and this is a primary ClassNode.- Parameters:
interfaces- an array ofClassNoderepresenting the interfaces, ornull- See Also:
-
getMixins
- Returns:
- the mixins associated with this
ClassNode
-
setMixins
-
getPermittedSubclasses
- Returns:
- permitted subclasses of sealed type, may initially be empty in early compiler phases
-
setPermittedSubclasses
-
getRecordComponents
Gets the record components of record type.- Returns:
RecordComponentNodeinstances- Since:
- 4.0.0
-
setRecordComponents
Sets the record components for record type.- Since:
- 4.0.0
-
addInterface
Adds an interface to the list of interfaces implemented by thisClassNode. If the interface is already implemented, this method has no effect. The interface is appended to the end of the current interfaces array.- Parameters:
node- theClassNoderepresenting the interface to add- See Also:
-
addMixin
-
addField
Adds aFieldNodeto this ClassNode. The field is added to the end of the field list and its declaring class is set to this node's redirect target. The field is registered in the internal field index for fast lookup by name.- Parameters:
node- theFieldNodeto add, must not benull- See Also:
-
addField
Creates and adds aFieldNodeto this ClassNode with the specified properties. The field is initialized with the given name, modifiers, type, and optional initial value expression. This is a convenience method that creates a FieldNode and adds it viaaddField(FieldNode).- Parameters:
name- the name of the fieldmodifiers- the access modifiers for the field (e.g., ACC_PUBLIC, ACC_PRIVATE)type- theClassNoderepresenting the field's typeinitialValue- the initial valueExpression, ornullif no initializer- Returns:
- the newly created
FieldNode - See Also:
-
addFieldFirst
Adds aFieldNodeto this ClassNode at the beginning of the field list. This method is similar toaddField(FieldNode)but prepends the field instead of appending it, which can be useful when field declaration order matters.- Parameters:
node- theFieldNodeto add first, must not benull- See Also:
-
addFieldFirst
Creates and adds aFieldNodeto the beginning of this ClassNode's field list with the specified properties. This is a convenience method for adding fields where declaration order is significant.- Parameters:
name- the name of the fieldmodifiers- the access modifiers for the field (e.g., ACC_PUBLIC, ACC_PRIVATE)type- theClassNoderepresenting the field's typeinitialValue- the initial valueExpression, ornullif no initializer- Returns:
- the newly created
FieldNode - See Also:
-
addProperty
Adds aPropertyNodeto this ClassNode. The property's associated field is also added to the field list, and the property itself is registered in the properties list. The property's declaring class is set to this node's redirect target.- Parameters:
node- thePropertyNodeto add, must not benull- See Also:
-
addProperty
public PropertyNode addProperty(String name, int modifiers, ClassNode type, Expression initialValue, Statement getterBlock, Statement setterBlock) Creates and adds aPropertyNodeto this ClassNode with the specified properties, or returns an existing property with the same name if one is already present. If a property with the given name exists, the method updates its getter block, setter block, and initial value expression if they are currentlynull. This prevents duplicate properties while allowing partial initialization across multiple calls.- Parameters:
name- the name of the propertymodifiers- the access modifiers for the property (e.g., ACC_PUBLIC, ACC_PRIVATE)type- theClassNoderepresenting the property's typeinitialValue- the initial valueExpression, ornullif no initializergetterBlock- the getter method'sStatementbody, ornullsetterBlock- the setter method'sStatementbody, ornull- Returns:
- the newly created
PropertyNodeor the existing property if one with this name is already present - See Also:
-
addMethod
Adds aMethodNodeto this ClassNode. The method is added to the internal methods list and registered by name in the methods map for fast lookup. The method's declaring class is set to this node's redirect target. This method does not check for duplicates.- Parameters:
node- theMethodNodeto add, must not benull- See Also:
-
addMethod
public MethodNode addMethod(String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) Creates and adds aMethodNodeto this ClassNode with the specified properties, but only if a method with the same name and parameter signature does not already exist. If a matching method is already declared in this class, it is returned without adding a new one. This method is useful for adding default method implementations (e.g.,getProperty(),invokeMethod()) where the class may already have a user-defined version.- Parameters:
name- the name of the methodmodifiers- the access modifiers (e.g., ACC_PUBLIC, ACC_STATIC)returnType- theClassNoderepresenting the return typeparameters- array ofParameters, or an empty array for no parametersexceptions- array of exceptionClassNodes that the method declares, or an empty arraycode- the method body as aStatement, ornull- Returns:
- the newly created
MethodNodeor an existing method if one matches the name and parameters - See Also:
-
addSyntheticMethod
public MethodNode addSyntheticMethod(String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) Adds a synthetic method as part of the compilation process. -
addConstructor
-
addConstructor
public ConstructorNode addConstructor(int modifiers, Parameter[] parameters, ClassNode[] exceptions, Statement code) -
addObjectInitializerStatements
Adds a statement to the object initializer.- Parameters:
statement- the statement to be added
-
addStaticInitializerStatements
-
positionStmtsAfterEnumInitStmts
-
getFields
Returns allFieldNodes declared in this ClassNode, including inherited fields. If this node is a proxy (has a redirect), the call is forwarded to the redirect target. The returned list includes fields from this class only, not from super classes.- Returns:
- an unmodifiable or mutable list of
FieldNodes associated with this ClassNode; an empty list if this class declares no fields - See Also:
-
getProperties
Returns allPropertyNodes declared in this ClassNode. If this node is a proxy (has a redirect), the call is forwarded to the redirect target. Properties are distinct from fields and represent a higher-level abstraction with getter/setter semantics.- Returns:
- a mutable list of
PropertyNodes associated with this ClassNode; an empty list if this class declares no properties - See Also:
-
getFieldIndex
Deprecated, for removal: This API element is subject to removal in a future version.for removal since 5.0.0; usegetField(String)orgetDeclaredField(String)insteadReturns the internal field index map for fast field lookup by name. This method is deprecated as field access should go throughgetField(String)orgetDeclaredField(String). The field index is an internal implementation detail and may change in future versions.- Returns:
- a map from field name to
FieldNode, ornullif no field index exists - See Also:
-
hasProperty
Tests whether a property with the given name exists in this ClassNode. This method searches through the properties list, comparing by name.- Parameters:
name- the name of the property to check- Returns:
trueif a property with the given name exists,falseotherwise- See Also:
-
getProperty
Finds aPropertyNodematching the given name in this ClassNode. This method searches through the properties list, comparing by name. Only direct properties of this class are searched, not inherited ones.- Parameters:
name- the name of the property to find- Returns:
- the
PropertyNodewith the given name, ornullif not found - See Also:
-
getMethods
Returns allMethodNodes declared in this ClassNode, including inherited and synthetic methods. If this node is a proxy (has a redirect), the call is forwarded to the redirect target. This list includes constructors and all instance and static methods defined for this class.- Returns:
- a list of all
MethodNodes associated with this ClassNode; an empty list if this class declares no methods - See Also:
-
getAbstractMethods
Returns a list of all abstractMethodNodes declared in this ClassNode. Abstract methods are obtained from the declared methods map and filtered to return only those with the abstract modifier set. This includes abstract methods from superclasses and implemented interfaces.- Returns:
- a list of abstract
MethodNodes (possibly empty); returns an empty list if there are no abstract methods - See Also:
-
getDeclaredMethodsMap
Returns all declaredMethodNodes from this ClassNode and its superclasses and interfaces. The methods are collected in a single map with method type descriptors as keys, allowing resolution of method overrides across the inheritance hierarchy. This method provides a complete view of all accessible methods.- Returns:
- a map from method type descriptor (name and signature) to
MethodNode; includes methods from superclasses and interfaces - See Also:
-
getAllDeclaredMethods
Returns all declaredMethodNodes from this ClassNode and its superclasses and interfaces as a list. This is a convenience method that collects all values from the declared methods map into a single list.- Returns:
- a list of all
MethodNodes declared in this class, superclasses, and interfaces; an empty list if no methods are found - See Also:
-
getDeclaredConstructors
-
getDeclaredConstructor
- Returns:
- the constructor matching the given parameters or
null
-
hasMethod
Tests whether a method with the given name and parameter signature exists in this class or any of its superclasses. This is a convenience method for checking method existence.- Parameters:
name- the name of the method to checkparameters- an array ofParameters representing the method signature, ornull/emptyfor methods with no parameters- Returns:
trueif a method with the given name and parameters exists,falseotherwise- See Also:
-
hasDeclaredMethod
Tests whether a method with the given name and parameter signature is declared directly in this class (not inherited from a superclass). This is a convenience method for checking method existence.- Parameters:
name- the name of the method to checkparameters- an array ofParameters representing the method signature, ornull/emptyfor methods with no parameters- Returns:
trueif a method with the given name and parameters is declared in this class,falseotherwise- See Also:
-
getDeclaredField
Finds aFieldNodematching the given name declared directly in this class. This method does not search superclasses; to include inherited fields, usegetField(String). If this node is a proxy (has a redirect), the call is forwarded to the redirect target.- Parameters:
name- the name of the field to find- Returns:
- the
FieldNodewith the given name declared in this class, ornullif not found - See Also:
-
getField
Finds aFieldNodematching the given name in this class or any of its superclasses. This method searches the inheritance hierarchy starting from this ClassNode and moving up through superclasses until a field with the matching name is found.- Parameters:
name- the name of the field to find- Returns:
- the
FieldNodewith the given name, ornullif not found in this class or any superclass - See Also:
-
getObjectInitializerStatements
-
getDeclaredMethods
Returns a list of allMethodNodes with the given name declared directly in this class. This method does not search superclasses; to include inherited methods, usegetMethods(String). If this node is a proxy (has a redirect), the call is forwarded to the redirect target. The list may be empty if no methods with the given name are declared in this class.- Parameters:
name- the name of the methods to find- Returns:
- a list of
MethodNodes with the given name (possibly empty) - See Also:
-
getMethods
Returns a list of allMethodNodes with the given name from this class and its superclasses. This method searches the inheritance hierarchy starting from this ClassNode and moving up through superclasses, collecting all methods with matching names. The list may be empty if no methods with the given name are found in the class hierarchy.- Parameters:
name- the name of the methods to find- Returns:
- a list of
MethodNodes with the given name from this class and its superclasses (possibly empty) - See Also:
-
getDeclaredMethod
Finds aMethodNodematching the given name and parameter signature declared directly in this class. This method does not search superclasses; to include inherited methods, usegetMethod(String, Parameter[]). Parameter matching is done by comparing parameter types using theparametersEqual(Parameter[], Parameter[])method.- Parameters:
name- the name of the method to findparameters- an array ofParameters representing the method signature, ornull/emptyfor methods with no parameters- Returns:
- the
MethodNodewith the given name and parameters, ornullif not found - See Also:
-
getMethod
Finds aMethodNodematching the given name and parameter signature in this class or any of its superclasses. This method searches the inheritance hierarchy starting from this ClassNode. Parameter matching is done by comparing parameter types using theparametersEqual(Parameter[], Parameter[])method.- Parameters:
name- the name of the method to findparameters- an array ofParameters representing the method signature, ornull/emptyfor methods with no parameters- Returns:
- the
MethodNodewith the given name and parameters, ornullif not found in this class or any superclass - See Also:
-
isDerivedFrom
- Parameters:
type- the ClassNode of interest- Returns:
- true if this node is derived from the given ClassNode
-
isDerivedFromGroovyObject
public boolean isDerivedFromGroovyObject()Returns whether thisClassNoderepresents a type that implements theGroovyObjectinterface. GroovyObject is the core interface that all Groovy objects implement, providing methods likegetProperty(),setProperty(), andinvokeMethod()for dynamic behavior. This method checks the class hierarchy to determine if GroovyObject is in the list of implemented interfaces.- Returns:
trueif this type directly or indirectly implementsGroovyObject;falseotherwise- See Also:
-
implementsAnyInterfaces
- Parameters:
classNodes- the class nodes for the interfaces- Returns:
trueif this type implements any of the given interfaces
-
implementsInterface
- Parameters:
classNode- the class node for the interface- Returns:
trueif this type implements the given interface
-
declaresAnyInterfaces
- Parameters:
classNodes- the class nodes for the interfaces- Returns:
trueif this type declares that it implements any of the given interfaces or if one of its interfaces extends directly/indirectly any of the given interfaces
-
declaresInterface
- Parameters:
classNode- the class node for the interface- Returns:
trueif this class declares that it implements the given interface or if one of its interfaces extends directly/indirectly the interface NOTE: Doesn't consider an interface to implement itself. I think this is intended to be called on ClassNodes representing classes, not interfaces.- See Also:
-
parametersEqual
@Deprecated(forRemoval=true, since="4.0.0") protected boolean parametersEqual(Parameter[] a, Parameter[] b) Deprecated, for removal: This API element is subject to removal in a future version. -
getGetterMethod
Finds a getterMethodNodematching the given name, optionally searching superclasses. A getter method is defined as a method with no parameters that returns a non-void type. For methods starting with "is", the return type must be boolean. Synthetic and bridge methods are disregarded in favor of the most specific real getter.- Parameters:
getterName- the name of the getter method to find- Returns:
- the getter
MethodNode, ornullif not found - See Also:
-
getGetterMethod
Finds a getterMethodNodematching the given name, optionally searching superclasses and interfaces. A getter method is defined as a method with no parameters that returns a non-void type. For methods starting with "is", the return type must be boolean. Synthetic and bridge methods are disregarded in favor of the most specific real getter.- Parameters:
getterName- the name of the getter method to findsearchSupers- iftrue, searches superclasses and interfaces for the getter; iffalse, searches only methods declared in this class- Returns:
- the getter
MethodNode, ornullif not found - See Also:
-
getSetterMethod
Finds a setterMethodNodematching the given name, optionally searching superclasses. A setter method is defined as a method with exactly one parameter that returns void. This method searches from this class up the inheritance hierarchy until a matching setter is found.- Parameters:
setterName- the name of the setter method to find- Returns:
- the setter
MethodNode, ornullif not found - See Also:
-
getSetterMethod
Finds a setterMethodNodematching the given name. A setter method is defined as a method with exactly one parameter. IfvoidOnlyistrue, the method must also return void. The method searches this class and superclasses for the first matching setter.- Parameters:
setterName- the name of the setter method to findvoidOnly- iftrue, only returns setter methods that return void; iffalse, accepts setters that return any type- Returns:
- the setter
MethodNode, ornullif not found - See Also:
-
hasPossibleMethod
Determines if the type has a possibly-matching instance method with the given name and arguments.- Parameters:
name- the name of the method of interestarguments- the arguments to match against- Returns:
- true if a matching method was found
-
tryFindPossibleMethod
-
hasPossibleStaticMethod
Checks if the given method has a possibly matching static method with the given name and arguments.- Parameters:
name- the name of the method of interestarguments- the arguments to match against- Returns:
trueif a matching method was found
-
renameField
-
removeField
Removes theFieldNodewith the given name from this ClassNode. This method removes the field from the internal field list and index. If this node is a proxy (has a redirect), the operation is performed on the redirect target.- Parameters:
oldName- the name of the field to remove- See Also:
-
removeMethod
Removes the givenMethodNodefrom this ClassNode. The method is removed from the internal methods list and the methods map. If this node is a proxy (has a redirect), the operation is performed on the redirect target.- Parameters:
node- theMethodNodeto remove- See Also:
-
removeConstructor
-
equals
Compares thisClassNodewith another object for equality. Two ClassNodes are considered equal if:- They are the same object (identity check)
- Both are ClassNode instances and either have identical redirects, identical component types (for arrays), or have matching text representations
-
hashCode
public int hashCode()Returns the hash code for thisClassNode. The hash code is based on the redirect's hash code if a redirect exists, or the text representation's hash code if this is a primary or array ClassNode. This ensures that equal ClassNodes (byequals(Object)) have equal hash codes, maintaining the hash code contract for use in hash-based collections. -
toString
Returns a string representation of this ClassNode for debugging and display purposes. For array types, appends "[]" to the component type's string representation. For generic types, includes generic type parameters (e.g., "List"). If this is a redirect node, includes arrow notation showing the redirect target. -
toString
Returns a string representation of this ClassNode with optional redirect information. For array types, appends "[]" to the component type's string representation. For generic types, includes generic type parameters (e.g., "List"). If showRedirectistrueand this is a redirect node, includes arrow notation showing the redirect target; otherwise the redirect information is omitted.- Parameters:
showRedirect- iftrue, includes redirect information in the output; iffalse, omits it- Returns:
- a string representation of this ClassNode
-
visitContents
-
isAbstract
public boolean isAbstract()Returns whether thisClassNoderepresents an abstract class. A class is abstract if theACC_ABSTRACTmodifier flag is set in its modifiers. Abstract classes cannot be instantiated directly; they serve as base types for subclasses. This method checks the actual modifier bits, independent of the source code syntax.- Returns:
trueif this class has the abstract modifier set;falseotherwise- See Also:
-
isInterface
public boolean isInterface()Returns whether thisClassNoderepresents an interface type. A class is an interface if theACC_INTERFACEmodifier flag is set in its modifiers. Interfaces define contracts for implementing classes without providing implementation details. Note that annotations are also interfaces (with theACC_ANNOTATIONflag also set).- Returns:
trueif this class is an interface;falseif it is a regular class- See Also:
-
isAnnotationDefinition
public boolean isAnnotationDefinition()Returns whether thisClassNoderepresents an annotation type (annotation definition). Annotation types are always interfaces with both theACC_INTERFACEandACC_ANNOTATIONmodifier flags set. They define metadata that can be attached to program elements. All annotation types are interfaces but not all interfaces are annotations.- Returns:
trueif this class is an annotation type;falseotherwise- See Also:
-
isEnum
public boolean isEnum()Returns whether thisClassNoderepresents an enumeration type. An enum class has theACC_ENUMmodifier flag set in its modifiers. Enumerations define a fixed set of named constants that can be iterated over at compile time.- Returns:
trueif this class is an enumeration;falseotherwise- See Also:
-
isRecord
Checks if theClassNodeinstance represents a nativerecord. Check instead for theRecordBaseannotation if looking for records and record-like classes currently being compiled.- Returns:
trueif the instance represents a nativerecord- Since:
- 4.0.0
-
isSealed
- Returns:
truefor native and emulated (annotation based) sealed classes- Since:
- 4.0.0
-
isResolved
public boolean isResolved()Determines whether this ClassNode has been resolved to an actual Java class. A ClassNode is considered resolved if it represents a realClassobject loaded at runtime, or if it has been redirected to a resolved ClassNode, or if it represents an array of resolved component types. During early compilation phases, unresolved ClassNodes may reference types that haven't been loaded yet.- Returns:
trueif this ClassNode has been resolved to a real class;falseif it still represents an unresolved reference
-
getTypeClass
Returns the concrete class this classnode relates to. However, this method is inherently unsafe as it may return null depending on the compile phase you are using. AST transformations should never use this method directly, but rather obtain a new class node usinggetPlainNodeReference().- Returns:
- the class this classnode relates to. May return null.
-
isArray
public boolean isArray()Determines whether this ClassNode represents an array type. A ClassNode is an array if its component type has been set. The component type represents the element type of the array (e.g., "int" for "int[]", or "String" for "String[]").- Returns:
trueif this ClassNode represents an array type;falseif it represents a scalar type
-
makeArray
Returns aClassNoderepresenting an array of the type represented by this. -
getComponentType
Returns the component type of this array ClassNode. If this ClassNode does not represent an array type, returnsnull. For array types, this returns theClassNoderepresenting the element type (e.g., for "String[]", returns the ClassNode for "String").- Returns:
- the
ClassNoderepresenting the array's element type, ornullif not an array
-
getOuterClass
Returns the outer class of thisClassNode, ornullif this is not an inner class. If this ClassNode has a redirect, returns the outer class from the redirect. This method traverses the class hierarchy upward to find the immediately enclosing class.- Returns:
- the outer
ClassNode, ornullif not an inner class - See Also:
-
getOuterClasses
Returns a list of all outer classes enclosing thisClassNodein hierarchical order. The innermost outer class appears first in the list. Returns an empty list if this is not an inner class. If this ClassNode has a redirect, the list is derived from the redirect. -
getOuterField
- Returns:
- the field on the outer class or
nullif this is not an inner class
-
getInnerClasses
Returns an iterator over the inner classes defined within thisClassNode. The iterator is backed by an unmodifiable view of the inner classes list. Returns an empty iterator if this class has no inner classes defined.- Returns:
- an
IteratorofInnerClassNodes defined in this class, nevernull - See Also:
-
addInnerClass(InnerClassNode)
-
getEnclosingMethod
Returns the enclosingMethodNodeof this local inner class, ornullif this is not a local inner class. Local inner classes are those declared within method bodies. If this ClassNode has a redirect, returns the enclosing method from the redirect.- Returns:
- the
MethodNodeenclosing this class, ornull - See Also:
-
setEnclosingMethod
Sets the enclosingMethodNodefor this local inner class. This is typically called when processing classes declared within method bodies.- Parameters:
enclosingMethod- theMethodNodeenclosing this class, ornull- See Also:
-
asGenericsType
-
getGenericsTypes
Returns the generic type parameters for thisClassNode, ornullif none are defined. Generic types represent type parameters and their bounds as declared in class definitions. For example, inclass List<T>, theGenericsTypearray would contain a single element representing the type parameterT.- Returns:
- an array of
GenericsTyperepresenting the type parameters, ornull - See Also:
-
setGenericsTypes
Sets the generic type parameters for thisClassNode. Setting generics types updates the generics usage indicator for this class. This method is typically called during compiler phases when type information becomes available.- Parameters:
genericsTypes- an array ofGenericsTyperepresenting the type parameters, ornull- See Also:
-
isGenericsPlaceHolder
public boolean isGenericsPlaceHolder() -
setGenericsPlaceHolder
public void setGenericsPlaceHolder(boolean placeholder) -
isUsingGenerics
public boolean isUsingGenerics() -
setUsingGenerics
public void setUsingGenerics(boolean usesGenerics) -
isScript
public boolean isScript()Returns whether thisClassNoderepresents a Groovy script body. A script is a special class that executes at the top level rather than requiring instantiation. This method checks both the direct flag and whether the class derives fromScript. During compilation, script bodies are compiled into classes that extend theScriptbase class.- Returns:
trueif this class represents a script;falseotherwise- See Also:
-
setScript
public void setScript(boolean script) Marks thisClassNodeas a script or removes the script flag. Setting this totrueindicates that this class represents a Groovy script that should be executed at the top level. This is used internally during compilation to identify script classes that need special treatment (e.g., extending the Script base class).- Parameters:
script-trueto mark as a script;falseto unmark- See Also:
-
isScriptBody
public boolean isScriptBody()Returns whether this inner class or closure was declared inside a script body. This flag distinguishes between inner classes/closures defined within a script's top-level code versus those defined within regular class methods. Script body context affects how local variable access and scoping rules are applied. This method follows redirects if present.- Returns:
trueif this inner class or closure is inside a script body;falseotherwise- See Also:
-
setScriptBody
public void setScriptBody(boolean scriptBody) Marks this inner class or closure as being declared inside a script body. When set totrue, indicates that the class definition occurs at the top level of a Groovy script (outside of any method or class definition). This affects variable scoping and how the compiler generates code for accessing enclosing scope variables. Typically used by the compiler during script class generation.- Parameters:
scriptBody-trueto mark as defined in script body;falseotherwise- See Also:
-
isStaticClass
public boolean isStaticClass()Returns whether this inner class or closure was declared inside a static method context. This flag identifies classes that are nested within static methods (as opposed to instance methods or top-level definitions). Inner classes in static contexts have different scoping rules and cannot access instance variables of the enclosing class. This method follows redirects if present.- Returns:
trueif this class is declared in a static method;falseotherwise- See Also:
-
setStaticClass
public void setStaticClass(boolean staticClass) Marks this inner class or closure as being declared in a static method context. When set totrue, indicates that this class definition occurs within a static method, affecting how the compiler generates access to enclosing class members. Static inner classes have restricted access to the enclosing class (only to static members).- Parameters:
staticClass-trueto mark as defined in a static context;falseotherwise- See Also:
-
isSyntheticPublic
public boolean isSyntheticPublic()Indicates that this class has been "promoted" to public by Groovy when in fact there was no public modifier explicitly in the source code. That is, it remembers that it has applied Groovy's "public classes by default" rule. This property is typically only of interest to AST transform writers.- Returns:
trueif node is public but had no explicit public modifier
-
setSyntheticPublic
public void setSyntheticPublic(boolean syntheticPublic) Marks thisClassNodeas having synthetic public visibility. When set totrue, indicates that this class was implicitly made public by Groovy's default visibility rule rather than having an explicitpublicmodifier in the source code. This distinction is important for AST transformations that need to preserve the original intent regarding visibility and access control.- Parameters:
syntheticPublic-trueif public was added by the compiler;falseif explicitly declared- See Also:
-
isAnnotated
public boolean isAnnotated()Returns whether thisClassNodehas been marked as annotated. This flag is set totruewhen annotations are added to the class viaAnnotatedNode.addAnnotation(AnnotationNode)or related methods. It serves as a quick indicator that the class carries metadata annotations, without requiring iteration through the full annotations list. The flag does not distinguish between different types of annotations (type annotations, method annotations, etc.).- Returns:
trueif this class has been marked as having annotations;falseotherwise- See Also:
-
setAnnotated
public void setAnnotated(boolean annotated) Marks thisClassNodeas having annotations attached to it. This flag is used internally by the compiler to track whether annotations have been added to the class. It should be set totruewhen annotations are added and may be used as an optimization to avoid scanning the annotations list for empty cases.- Parameters:
annotated-trueto mark as having annotations;falseto clear the flag- See Also:
-
getAnnotations
Description copied from class:AnnotatedNodeReturns all annotations attached to this AST node. Annotations are runtime-visible or source-level metadata attached to language elements.- Overrides:
getAnnotationsin classAnnotatedNode- Returns:
- list of
AnnotationNode, or empty list if none
-
getAnnotations
Description copied from class:AnnotatedNodeReturns annotations of a specific type attached to this AST node. Filters the annotation list by the provided type.- Overrides:
getAnnotationsin classAnnotatedNode- Parameters:
type- the annotation type to filter by- Returns:
- list of matching
AnnotationNode, or empty list if none
-
getTypeAnnotations
-
getTypeAnnotations
-
addTypeAnnotation
-
addTypeAnnotations
-
addTransform
-
getTransforms
-
getField(String)orgetDeclaredField(String)instead