Hello,I would like to ask what is the meaning of the comments of the getEnclosingElement()
method in the Element
interface, I do not quite understand. javadoc as follows:
Returns the innermost element within which this element is, loosely speaking, enclosed.
If this element is one whose declaration is lexically enclosed immediately within the declaration of another element, that other element is returned.
If this is a top-level type, its package is returned.
If this is a package, null is returned.
- If this is a type parameter, the generic element of the type parameter is returned.
- If this is a method or constructor parameter, the executable element which declares the parameter is returned.
Annotations can be used on classes, variables (global or local), methods, etc., but I don't know the correspondence between annotations and Element subclass. Thanks!!!
An Element
can represent, as of Java 13:
- A module declaration -
ModuleElement
- A package declaration -
PackageElement
- An interface, class, enum, or annotation type -
TypeElement
- A constructor, method, or initializer -
ExecutableElement
- A field, enum constant, method or constructor parameter, local variable, resource variable, or exception parameter -
VariableElement
- A type parameter -
TypeParameterElement
Each of these elements can have annotations present. For example:
module-info.java:
@Foobar
module example {
exports com.example;
}
package-info.java:
@Foobaz
package com.example;
Foo.java:
package com.example;
@Baz
public class Foo<@Qux T> {
private final T bar;
public Foo(T bar) {
this.bar = bar;
}
@Override
public String toString() {
return "Foo{bar= " + bar + "}";
}
}
- The module
example
, which would be aModuleElement
, has a@Foobar
annotation present. - The package
com.example
, which would be aPackageElement
, has a@Foobaz
annotation present. - The class
Foo
, which would be aTypeElement
, has a@Baz
annotation present. - The type parameter
T
, which would be aTypeParameterElement
, has a@Qux
annotation present. - The field
bar
, which would be aVariableElement
, has no annotations present. - The constructor
#Foo(T)
, which would be anExecutableElement
, has no annotations present. - The constructor's parameter
bar
, which would be aVariableElement
, has no annotations present. - The method
#toString()
, which would be anExectuableElement
, has an@Override
annotation present.
You can get the annotations present on these elements via the methods of the AnnotatedConstruct
interface, which Element
extends.
The method Element#getEnclosingElement()
returns, unsurprisingly, the Element
which encloses the current Element
, if any. So if you were to invoke that method on the ExecutableElement
representing the method #toString()
then you'd get the TypeElement
representing the class Foo
.