Class ClassNode
- All Implemented Interfaces:
GroovydocHolder<AnnotatedNode>,NodeMetaDataHandler
- Direct Known Subclasses:
DecompiledClassNode,InnerClassNode,IntersectionTypeClassNode,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.
getOuterClassType() / setOuterClassType(ClassNode) are
likewise not proxied: they record the parameterized enclosing type of a
JLS 4.5 rare type use (Outer<T>.Inner), distinct from
getOuterClass() which is the enclosing class of a nested class
declaration.
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected Class<?>Reflection class this node wraps, ornullfor a source class, a placeholder, or an unresolved array.static final ClassNode[]Shared zero-length array for call sites that need a type list but have no classes, such as no superinterfaces or no declared exceptions.protected booleantruewhen this node was built as a Groovy source class the compiler emits.protected final ObjectLock for the one-time fill-in of members copied from a reflection class.static final ClassNodeSentinel type of asuper()constructor call.static final ClassNodeSentinel type of athis()constructor call.Fields 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) Creates a constructor from the given parts and appends it to the resolved class.voidAppends a constructor to the resolved class and sets that constructor's declaring class to the resolved node.addField(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.voidAppends a mixin to the resolved class when an equal mixin is not already present.voidaddObjectInitializerStatements(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) Adds statements to the synthetic static initializer<clinit>, creating that method when the class does not already have one.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) Records an AST node as a reason to run a global transform, whentransformcarriesGroovyASTTransformation.voidaddTypeAnnotation(AnnotationNode annotation) Appends a type-use annotation to this node and marks the node annotated.voidaddTypeAnnotations(List<AnnotationNode> annotations) Adds each type-use annotation throughaddTypeAnnotation(org.codehaus.groovy.ast.AnnotationNode), in order.Views this node as a generic type argument.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.Collects the interfaces of this type into aLinkedHashSet, keeping the order of first encounter and dropping a repeat.Returns all annotations attached to this AST node.getAnnotations(ClassNode type) Returns annotations of a specific type attached to this AST node.Returns the compile unit of the module that owns this class.Returns the component type of this array ClassNode.getDeclaredConstructor(Parameter[] parameters) Returns the constructors declared on the resolved class.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.Returns the module recorded on the resolved class, ornullwhensetModule(org.codehaus.groovy.ast.ModuleNode)did not store one.getName()Returns the fully-qualified name of this class after following any redirects.Returns the text ofgetName()after the last dot.Returns the instance-initializer statements stored on this node.Returns the outer class of thisClassNode, ornullif this is not an inner class.Returns a list of all outer classes enclosing thisClassNodein hierarchical order.For a JLS 4.5 rare typeOuter<T>.Inner, the parameterized enclosing type stored on this node (type-use, not declaration; not node metadata and not redirected).getOuterField(String name) Returns the package ofgetModule(), ornullwhen this class has no module.Returns the package portion ofgetName(), which follows the redirect.Returns a non-primary proxy that redirects toredirect(), so generics or type annotations can be added without mutating the canonical class.getPlainNodeReference(boolean skipPrimitives) Builds a non-primary proxy that redirects toredirect().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) Returns the live map from transform class to the AST nodes that scheduled it for one compilation phase.Returns a copy of the type-use annotations stored on this node.getTypeAnnotations(ClassNode type) Returns the type-use annotations on this node whose annotation class is equal totype.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 name stored on this node, without following a redirect.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.booleanReports whethergetName()has a dot after its first character.booleanhasPossibleMethod(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.booleanReports whether this node stands for a type variable rather than a class.booleanReturns 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()booleanisStatic()Returns whether thisClassNoderepresents a static class.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.booleanReports the generics-usage flag stored on this node, without following a redirect.Returns 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.for removal since 4.0.0; callParameterUtils.parametersEqual(org.codehaus.groovy.ast.Parameter[], org.codehaus.groovy.ast.Parameter[])insteadvoidpositionStmtsAfterEnumInitStmts(List<Statement> staticFieldInitializerStatements) Inserts static field initializers into<clinit>immediately after every binary expression whose left side is the synthetic$VALUESfield.redirect()Returns theClassNodethis node is a proxy for or the node itself.voidRemoves a constructor from the declared constructors of the resolved class.voidremoveField(String oldName) Removes theFieldNodewith the given name from this ClassNode.voidremoveMethod(MethodNode node) Removes the givenMethodNodefrom this ClassNode.voidrenameField(String oldName, String newName) Rebinds the resolved class's field index fromoldNametonewName.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.for removal since 5.0.0; the compile unit is no longer stored on the class nodevoidsetEnclosingMethod(MethodNode enclosingMethod) Sets the enclosingMethodNodefor this local inner class.voidsetGenericsPlaceHolder(boolean placeholder) Sets or clears the type-variable flag on this node.voidsetGenericsTypes(GenericsType[] genericsTypes) Sets the generic type parameters for thisClassNode.voidsetInterfaces(ClassNode[] interfaces) Sets the interfaces implemented by thisClassNode.voidReplaces the mixins of the resolved class.voidsetModifiers(int modifiers) Sets the modifier flags for thisClassNode.voidsetModule(ModuleNode module) Records the module that owns this source class.Sets the fully-qualified name of this class, delegating to the redirect if one exists.voidsetOuterClassType(ClassNode outer) Records the parameterized enclosing type of a JLS 4.5 rare type on this node.voidsetPermittedSubclasses(List<ClassNode> permittedSubclasses) Replaces the permitted-subclass list stored on the resolved node.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) Sets the generics-usage flag on this node, including clearing it.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) Searches for one method on this type that can accept the arguments.voidvisitContents(GroovyClassVisitor visitor) Visits the members of the resolved class in order: properties, fields, declared constructors, then methods.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
Shared zero-length array for call sites that need a type list but have no classes, such as no superinterfaces or no declared exceptions. -
THIS
Sentinel type of athis()constructor call. The call is recognized by identity with this node, which is a distinctObjectclass node and not the enclosing class. -
SUPER
Sentinel type of asuper()constructor call. The call is recognized by identity with this node, which is a distinctObjectclass node and not the superclass. -
isPrimaryNode
protected boolean isPrimaryNodetruewhen this node was built as a Groovy source class the compiler emits. Reflection classes, synthetic arrays, and plain references clear the flag.setRedirect(ClassNode)rejects a primary node, andsetModule(org.codehaus.groovy.ast.ModuleNode)stores the module only while the flag is set. The flag is not read through a redirect;isPrimaryClassNode()follows one. -
lazyInitLock
Lock for the one-time fill-in of members copied from a reflection class. Subclasses that initialize lazily synchronize on this same object. Each class node has its own lock. -
clazz
Reflection class this node wraps, ornullfor a source class, a placeholder, or an unresolved array.isResolved()andgetTypeClass()treat a non-null value as resolved for this instance before they consult a redirect.
-
-
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
Returns a non-primary proxy that redirects toredirect(), so generics or type annotations can be added without mutating the canonical class. A primitive is returned asthis. UsegetPlainNodeReference(boolean)to force a proxy for a primitive.- Returns:
- this node when it is a primitive, otherwise a new redirecting proxy
-
getPlainNodeReference
Builds a non-primary proxy that redirects toredirect(). The proxy keeps this node's own unresolved name, modifiers, and unresolved superclass, and has no interfaces or mixins of its own; getters that follow the redirect see the canonical class. An array proxy takes its component type from the redirect, and a recorded outer class type is copied onto the proxy. WhenskipPrimitivesis true and this node is a primitive,thisis returned so the shared primitive node keeps its identity.- Parameters:
skipPrimitives-trueto return a primitive node unchanged- Returns:
thisfor a skipped primitive, otherwise a new proxy
-
getModule
Returns the module recorded on the resolved class, ornullwhensetModule(org.codehaus.groovy.ast.ModuleNode)did not store one. The lookup followsredirect().- Returns:
- the owning module, or
null
-
setModule
Records the module that owns this source class. The module is stored as metadata on this node only whenisPrimaryNodeis set; a placeholder or reflection class ignores the call.getModule()finds it by following the redirect back to this node.- Parameters:
module- the module to associate with this primary class
-
getCompileUnit
Returns the compile unit of the module that owns this class. A redirect is followed. The unit is taken from the module stored bysetModule(org.codehaus.groovy.ast.ModuleNode), not fromsetCompileUnit(org.codehaus.groovy.ast.CompileUnit).- Returns:
- the owning compile unit, or
nullwhen the class has no module
-
setCompileUnit
Deprecated, for removal: This API element is subject to removal in a future version.for removal since 5.0.0; the compile unit is no longer stored on the class nodeWalks the redirect chain and discardscu. The node at the end of the chain ignores the argument, so the compile unit is never stored here.getCompileUnit()reads it from the module.- Parameters:
cu- unused compile unit
-
getPackage
Returns the package ofgetModule(), ornullwhen this class has no module.- Returns:
- the package node, or
null
-
getPackageName
Returns the package portion ofgetName(), which follows the redirect. The portion is the text before the last dot, so an inner-class$suffix stays in the simple name. A name with no dot after its first character is treated as the default package.- Returns:
- the package name, or
nullfor the default package
-
hasPackageName
public boolean hasPackageName()Reports whethergetName()has a dot after its first character. A default-package class, whose redirected name has no such dot, returnsfalse.- Returns:
truewhen the redirected name includes a package
-
getNameWithoutPackage
Returns the text ofgetName()after the last dot. When the redirected name has no dot after its first character, that whole name is returned. An inner class keeps its$suffix, sopkg.Outer$InneryieldsOuter$Inner.- Returns:
- the class name without its package
-
getUnresolvedName
Returns the name stored on this node, without following a redirect. A placeholder can still report the name it was created with aftergetName()reports the resolved class. A type variable is printed from this name.- Returns:
- this node's own name, which may be unresolved
-
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
Collects the interfaces of this type into aLinkedHashSet, keeping the order of first encounter and dropping a repeat. If this node is itself an interface, it is included first. The walk then followsgetInterfaces()of this node and of each interface reached that way, depth-first. Interfaces that appear only on a superclass are not visited.- Returns:
- the interfaces, never
null
-
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
Replaces the mixins of the resolved class. A redirect is written through. The array is stored as given and is not copied;nullclears it.- Parameters:
mixins- the mixin array to store, ornull
-
getPermittedSubclasses
- Returns:
- permitted subclasses of sealed type, may initially be empty in early compiler phases
-
setPermittedSubclasses
Replaces the permitted-subclass list stored on the resolved node. A redirect is written through, and the list is stored as given.getPermittedSubclasses()returns the list held after a reflection class is initialized, which may replace a list stored before that initialization.- Parameters:
permittedSubclasses- the classes a sealed type permits
-
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
Appends a mixin to the resolved class when an equal mixin is not already present. An existing match leaves the mixin list unchanged.- Parameters:
node- the mixin to add
-
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
Appends a constructor to the resolved class and sets that constructor's declaring class to the resolved node. The constructor list is created on first use. A constructor with the same parameters is not detected or reused.- Parameters:
node- the constructor to add
-
addConstructor
public ConstructorNode addConstructor(int modifiers, Parameter[] parameters, ClassNode[] exceptions, Statement code) Creates a constructor from the given parts and appends it to the resolved class. A constructor with the same parameters is not reused; the new node is always added.- Parameters:
modifiers- the constructor modifiersparameters- the parameters, or an empty arrayexceptions- the declared exception types, or an empty arraycode- the constructor body, ornull- Returns:
- the constructor that was added
-
addObjectInitializerStatements
Adds a statement to the object initializer.- Parameters:
statement- the statement to be added
-
addStaticInitializerStatements
Adds statements to the synthetic static initializer<clinit>, creating that method when the class does not already have one. WhenfieldInitis false the statements are appended, which is where a static initializer block goes. WhenfieldInitis true they are placed in front of the statements already in the initializer, andstatementsis mutated to hold that combined sequence.- Parameters:
statements- the statements to add; mutated whenfieldInitis truefieldInit-truefor static field initializers, which precede other static statements
-
positionStmtsAfterEnumInitStmts
Inserts static field initializers into<clinit>immediately after every binary expression whose left side is the synthetic$VALUESfield. That expression marks the end of the generated enum constants. The initializer is created when the class does not have one. When its body is not a block, or it contains no such expression, the statements are not inserted.- Parameters:
staticFieldInitializerStatements- initializers of explicitly declared static fields
-
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
Returns the constructors declared on the resolved class. A redirect is followed and a reflection class is initialized first. Superclass constructors are not included. The list is created empty when the class has none, and it is the live list updated by adding a constructor and byremoveConstructor(org.codehaus.groovy.ast.ConstructorNode).- Returns:
- the mutable declared constructors, never
null
-
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
Returns the instance-initializer statements stored on this node. The list is created on first access and is the live storageaddObjectInitializerStatements(Statement)appends to. A redirect is not followed, and a reflection class is not initialized to fill the list.- Returns:
- the mutable initializer statements, never
null
-
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.for removal since 4.0.0; callParameterUtils.parametersEqual(org.codehaus.groovy.ast.Parameter[], org.codehaus.groovy.ast.Parameter[])insteadCompares parameter lists by length and declared type. Types are compared with class-node equality, so a primitive and its wrapper do not match. Delegates toParameterUtils.parametersEqual(org.codehaus.groovy.ast.Parameter[], org.codehaus.groovy.ast.Parameter[]).- Parameters:
a- the first parameter listb- the second parameter list- Returns:
truewhen both lists have the same length and equal parameter types
-
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
Searches for one method on this type that can accept the arguments.A
TupleExpressionsupplies the argument list; any other expression counts as a single argument. A spread is not expanded, so the count can be smaller than the number of values passed at runtime. The search walks this class and then each superclass. A candidate matches when the argument count equals the parameter count, or the last parameter is an array and the argument count reaches that parameter, so the array takes any arguments beyond it, including none. Each argument type must be derived from the parameter type in that position, or from the array component type for a variable-arity tail. Static and non-public methods take part in this walk. UnlikehasPossibleMethod(java.lang.String, org.codehaus.groovy.ast.expr.Expression), argument types are checked.The first match is kept. A second match found while still scanning this class yields
null. Once the scan has moved to a superclass, a second match also yieldsnullwhen the first match does not have exactly one parameter per argument. When it does, differing parameter types yieldnullas well; equal types, using the superclass method's trailing array component after its last fixed parameter, leave the first match in place.When the class hierarchy has no match and
getInterfaces()is non-empty, the first public instance method on those interfaces and their superinterfaces with a compatible arity and argument types is returned. Interfaces that appear only on a superclass are not searched, and a second interface method does not cancel the first.- Parameters:
name- the method namearguments- the call arguments, usually aTupleExpression- Returns:
- the selected method, or
nullwhen none matches or the class hierarchy is ambiguous
-
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
Rebinds the resolved class's field index fromoldNametonewName. The indexed field node is not renamed and the field list is not reordered, so only lookup through the index observes the new name. A name that is not in the index is recorded asnulland replaces whatever was stored undernewName. When the class has no field index yet, the call does nothing.- Parameters:
oldName- the index key to removenewName- the index key that receives the removed entry
-
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
Removes a constructor from the declared constructors of the resolved class. Comparison is by identity. A constructor that is not in the list leaves the list unchanged.- Parameters:
node- the constructor node to remove
-
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
Visits the members of the resolved class in order: properties, fields, declared constructors, then methods. The class node itself and its inner classes are not visited. Each method is visited once, including a method added while another method is being visited. Methods already seen are tracked by identity, and the method list is scanned again until no unseen method remains.- Parameters:
visitor- the visitor that receives each member
-
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:
-
isStatic
public boolean isStatic()Returns whether thisClassNoderepresents a static class. A class is static if theACC_STATICmodifier flag is set in its modifiers. Static nested classes have no enclosing instance; they can be used without an instance of the enclosing class. This method checks the actual modifier bits, independent of the source code syntax.- Returns:
trueif this class has the static modifier set;falseotherwise- Since:
- 6.0.0
- 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
public boolean 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. -
getOuterClassType
For a JLS 4.5 rare typeOuter<T>.Inner, the parameterized enclosing type stored on this node (type-use, not declaration; not node metadata and not redirected). Distinct fromgetOuterClass(), which is the enclosing class of a nested class declaration. Copied bygetPlainNodeReference().- Returns:
- the parameterized enclosing type, or
nullif this is not a rare type - Since:
- 6.0.0
-
setOuterClassType
Records the parameterized enclosing type of a JLS 4.5 rare type on this node. Does not write throughredirect().- Parameters:
outer- the parameterizedOuter<T>node;nullclears it- Since:
- 6.0.0
-
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
Views this node as a generic type argument. A node that is not a type-variable placeholder becomes a generics type with no bounds. A placeholder whose stored generics type already has upper bounds returns that same object. Otherwise a new generics type is built with this node as the type variable and the redirect, or this node when there is no redirect, as its upper bound. A generic declaration already stored on the placeholder is copied onto that new type.- Returns:
- a generics type representing this node
-
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()Reports whether this node stands for a type variable rather than a class. The flag lives on this node and is not read from the redirect.- Returns:
truewhensetGenericsPlaceHolder(boolean)has marked this node as a placeholder
-
setGenericsPlaceHolder
public void setGenericsPlaceHolder(boolean placeholder) Sets or clears the type-variable flag on this node. Setting it also marks the node as using generics. Clearing it does not turn that mark off.- Parameters:
placeholder-truewhen this node stands for a type variable
-
isUsingGenerics
public boolean isUsingGenerics()Reports the generics-usage flag stored on this node, without following a redirect. The flag is raised when type parameters or a placeholder are set, and when a primary node's superclass or interfaces already use generics. Those updates do not clear it.- Returns:
truewhen this node has been marked as using generics
-
setUsingGenerics
public void setUsingGenerics(boolean usesGenerics) Sets the generics-usage flag on this node, including clearing it. UnlikesetGenericsTypes(org.codehaus.groovy.ast.GenericsType[])andsetGenericsPlaceHolder(boolean), the argument replaces the previous value.- Parameters:
usesGenerics-trueto mark the node as using generics
-
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
Returns a copy of the type-use annotations stored on this node. A redirect is not followed: type-use annotations belong to the use, not to the canonical class. The copy does not observe later additions.- Returns:
- a new list of type-use annotations, empty when none were added
-
getTypeAnnotations
Returns the type-use annotations on this node whose annotation class is equal totype. A redirect is not followed. The result is a new list.- Parameters:
type- the annotation class to select- Returns:
- a new list of matching type-use annotations, possibly empty
-
addTypeAnnotation
Appends a type-use annotation to this node and marks the node annotated. The annotation is stored here and not on the redirect target. A canonical class cannot carry type-use annotations, so the call fails when this node is not a redirect and it is resolved or primary. ThrowsNullPointerExceptionifannotationisnull.- Parameters:
annotation- the type-use annotation to add
-
addTypeAnnotations
Adds each type-use annotation throughaddTypeAnnotation(org.codehaus.groovy.ast.AnnotationNode), in order. An empty list does nothing. Each element is subject to the same rejection of a resolved or primary non-redirect.- Parameters:
annotations- the type-use annotations to add
-
addTransform
Records an AST node as a reason to run a global transform, whentransformcarriesGroovyASTTransformation. The node is stored under that transform class, in insertion order, in the map for the annotation'sCompilePhase. A node already recorded for that phase is ignored. A transform class without the annotation is ignored. The map lives on this node and is not redirected.- Parameters:
transform- the transform class to schedulenode- the AST node that triggered it, usually the annotation use
-
getTransforms
Returns the live map from transform class to the AST nodes that scheduled it for one compilation phase. The first call creates an empty map for every phase, so a phase with no transforms yields an empty map rather thannull. The map is the storageaddTransform(java.lang.Class<? extends org.codehaus.groovy.transform.ASTTransformation>, org.codehaus.groovy.ast.ASTNode)updates, and it is not redirected.- Parameters:
phase- the compilation phase to query- Returns:
- the mutable map of transform class to triggering nodes for
phase
-
getField(String)orgetDeclaredField(String)instead