下面列出了怎么用javax.lang.model.element.Element的API类实例代码及写法,或者点击链接到github查看源代码。
private boolean versionNameConditionMet(final String versionName, final Element element) {
// Drop out quickly if there's no versionName set otherwise the try/catch below is doomed to fail.
if (versionName.isEmpty()) return false;
int comparison;
try {
final Version conditionVersion = Version.valueOf(versionName);
final Version currentVersion = Version.valueOf(this.versionName);
comparison = Version.BUILD_AWARE_ORDER.compare(conditionVersion, currentVersion);
} catch (final IllegalArgumentException | com.github.zafarkhaja.semver.ParseException e) {
messager.printMessage(Diagnostic.Kind.ERROR, String.format("Failed to parse versionName: %1$s. " +
"Please use a versionName that matches the specification on http://semver.org/", versionName),
element);
// Assume the break condition is met if the versionName is invalid.
return true;
}
return !versionName.isEmpty() && comparison <= 0;
}
@Override
public Integer visitDeclared(DeclaredType t, Set<Element> visiting) {
Element element = t.asElement();
if (visiting.contains(element)) {
return 0;
}
Set<Element> newVisiting = new HashSet<Element>(visiting);
newVisiting.add(element);
int result = hashKind(HASH_SEED, t);
result *= HASH_MULTIPLIER;
result += t.asElement().hashCode();
result *= HASH_MULTIPLIER;
result += t.getEnclosingType().accept(this, newVisiting);
result *= HASH_MULTIPLIER;
result += hashList(t.getTypeArguments(), newVisiting);
return result;
}
/**
* Construct a new ConstructorBuilder.
*
* @param context the build context.
* @param typeElement the class whoses members are being documented.
* @param writer the doclet specific writer.
*/
private ConstructorBuilder(Context context,
TypeElement typeElement,
ConstructorWriter writer) {
super(context);
this.typeElement = typeElement;
this.writer = writer;
visibleMemberMap = configuration.getVisibleMemberMap(typeElement,
VisibleMemberMap.Kind.CONSTRUCTORS);
constructors = visibleMemberMap.getMembers(typeElement);
for (Element ctor : constructors) {
if (utils.isProtected(ctor) || utils.isPrivate(ctor)) {
writer.setFoundNonPubConstructor(true);
}
}
}
public static List<Element> getAnnotatedMembers( final String annotationName,
final AnnotationModelHelper helper )
{
final List<Element> result = new LinkedList<Element>();
try {
helper.getAnnotationScanner().findAnnotations(
annotationName,
EnumSet.of(ElementKind.FIELD, ElementKind.METHOD),
new AnnotationHandler() {
@Override
public void handleAnnotation(TypeElement type,
Element element, AnnotationMirror annotation)
{
result.add(element);
}
});
}
catch (InterruptedException e) {
FieldInjectionPointLogic.LOGGER.warning("Finding annotation "+
annotationName+" was interrupted"); // NOI18N
}
return result;
}
/**
* Adds {@code element} and its enclosed elements to {@code annotatedElements} if they are
* annotated with any annotations in {@code annotationTypes}. Does not traverse to member types of
* {@code element}, so that if {@code Outer} is passed in the example below, looking for
* {@code @X}, then {@code Outer}, {@code Outer.foo}, and {@code Outer.foo()} will be added to the
* multimap, but neither {@code Inner} nor its members will.
*
* <pre><code>
* {@literal @}X class Outer {
* {@literal @}X Object foo;
* {@literal @}X void foo() {}
* {@literal @}X static class Inner {
* {@literal @}X Object bar;
* {@literal @}X void bar() {}
* }
* }
* </code></pre>
*/
private static void findAnnotatedElements(
Element element,
ImmutableSet<TypeElement> annotationTypes,
ImmutableSetMultimap.Builder<TypeElement, Element> annotatedElements) {
for (Element enclosedElement : element.getEnclosedElements()) {
if (!enclosedElement.getKind().isClass() && !enclosedElement.getKind().isInterface()) {
findAnnotatedElements(enclosedElement, annotationTypes, annotatedElements);
}
}
// element.getEnclosedElements() does NOT return parameter elements
if (element instanceof ExecutableElement) {
for (Element parameterElement : asExecutable(element).getParameters()) {
findAnnotatedElements(parameterElement, annotationTypes, annotatedElements);
}
}
for (TypeElement annotationType : annotationTypes) {
if (isAnnotationPresent(element, annotationType)) {
annotatedElements.put(annotationType, element);
}
}
}
public ReferenceTransformer(WorkingCopy info, ElementKind kind,
MemberSearchResult result, String name, Element target) {
this.kind = kind;
this.name = name;
this.copy = info;
this.target = target;
if (result != null) {
ElementHandle<? extends Element> s = result.getShadowed();
if (s == null) {
s = result.getOverriden();
}
if (s != null) {
this.shadowed = s.resolve(info);
}
s = result.getShadowedGate();
if (s != null) {
this.shadowedGate = result.getShadowedGate().resolve(info);
}
}
}
@Override
@CheckForNull
public Void visitMethod(@NonNull final MethodTree node, @NonNull final Map<Pair<BinaryName,String>, UsagesData<String>> p) {
Element old = enclosingElement;
try {
enclosingElement = ((JCTree.JCMethodDecl) node).sym;
if (enclosingElement != null && enclosingElement.getKind() == ElementKind.METHOD) {
mainMethod |= SourceUtils.isMainMethod((ExecutableElement) enclosingElement);
// do not add idents for constructors, they always match their class' name, which is added as an ident separately
addIdent(activeClass.peek(), node.getName(), p, true);
}
return super.visitMethod(node, p);
} finally {
enclosingElement = old;
}
}
/**
* Check if the given class or any of its super classes have a super method with the given name.
* Private methods are ignored since the generated subclass can't call super on those.
*/
protected boolean hasSuperMethod(TypeElement classElement, Element attribute) {
if (!Utils.isEpoxyModel(classElement.asType())) {
return false;
}
for (Element subElement : SynchronizationKt.getEnclosedElementsThreadSafe(classElement)) {
if (subElement.getKind() == ElementKind.METHOD) {
ExecutableElement method = (ExecutableElement) subElement;
List<VariableElement> parameters = SynchronizationKt.getParametersThreadSafe(method);
if (!method.getModifiers().contains(Modifier.PRIVATE)
&& method.getSimpleName().toString().equals(attribute.getSimpleName().toString())
&& parameters.size() == 1
&& parameters.get(0).asType().equals(attribute.asType())) {
return true;
}
}
}
Element superClass = KotlinUtilsKt.superClassElement(classElement, typeUtils);
return (superClass instanceof TypeElement)
&& hasSuperMethod((TypeElement) superClass, attribute);
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(Annotation.class)) {
try {
TypeElement cls = (TypeElement) element;
PackageElement pkg = (PackageElement) cls.getEnclosingElement();
String clsSimpleName = getGeneratedClassName(cls, prefix);
String pkgName = pkg.getQualifiedName().toString();
FileObject sourceFile = createFile(pkgName, clsSimpleName, element);
BufferedWriter w = new BufferedWriter(sourceFile.openWriter());
try {
w.append("package ").append(pkgName).append(";");
w.newLine();
appendClassAnnotations(w);
w.append("public class ").append(clsSimpleName);
appendBody(pkgName, clsSimpleName, w);
} finally {
w.close();
}
} catch (IOException e) {
e.printStackTrace();
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage(), element);
}
}
return false; // not "claimed" so multiple processors can be tested
}
private void resolveResourceVariable(final WorkingCopy wc, TreePath tp, TreeMaker make, TypeMirror proposedType) {
final String name = ((IdentifierTree) tp.getLeaf()).getName().toString();
final Element el = wc.getTrees().getElement(tp);
if (el == null) {
return;
}
if (tp.getParentPath().getLeaf().getKind() != Kind.ASSIGNMENT) {
//?
return ;
}
AssignmentTree at = (AssignmentTree) tp.getParentPath().getLeaf();
VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(proposedType), at.getExpression());
wc.rewrite(at, vt);
}
private void bindingMembersCheck( WebBeansModel model ) {
TypeMirror mirror = model.resolveType("foo.TestClass1");
Element clazz = ((DeclaredType) mirror).asElement();
List<? extends Element> children = clazz.getEnclosedElements();
List<ExecutableElement> methods = ElementFilter.methodsIn( children );
assertEquals(2, methods.size());
for (ExecutableElement method : methods) {
Name simpleName = method.getSimpleName();
List<VariableElement> eventInjectionPoints = model.
getEventInjectionPoints( method, (DeclaredType) mirror);
assertEquals("Observer "+simpleName+" matches "+eventInjectionPoints.size()
+" events. But should match exactly one", 1, eventInjectionPoints.size());
VariableElement variableElement = eventInjectionPoints.get(0);
TypeElement containingType = model.getCompilationController().
getElementUtilities().enclosingTypeElement( variableElement);
Name varName = variableElement.getSimpleName();
assertEquals("Event injection point should be inside class foo.Clazz," +
"but found inside "+ containingType.getQualifiedName(),
"foo.Clazz", containingType.getQualifiedName().toString());
assertEquals("Observer method "+simpleName+" should match to" +
" event field 'event', but found :"+varName, "event", varName.toString());
}
}
public OneToManyImpl(final AnnotationModelHelper helper, final Element element, AnnotationMirror oneToManyAnnotation, String name, Map<String, ? extends AnnotationMirror> annByType) {
this.name = name;
AnnotationParser parser = AnnotationParser.create(helper);
parser.expectClass("targetEntity", new DefaultProvider() { // NOI18N
public Object getDefaultValue() {
return EntityMappingsUtilities.getCollectionArgumentTypeName(helper, element);
}
});
parser.expectEnumConstantArray("cascade", helper.resolveType("javax.persistence.CascadeType"), new ArrayValueHandler() { // NOI18N
public Object handleArray(List<AnnotationValue> arrayMembers) {
return new CascadeTypeImpl(arrayMembers);
}
}, parser.defaultValue(new CascadeTypeImpl()));
parser.expectEnumConstant("fetch", helper.resolveType("javax.persistence.FetchType"), parser.defaultValue("LAZY")); // NOI18N
parser.expectString("mappedBy", parser.defaultValue("")); // NOI18N
parseResult = parser.parse(oneToManyAnnotation);
joinTable = new JoinTableImpl(helper, annByType.get("javax.persistence.JoinTable")); // NOI18N
joinColumnList = EntityMappingsUtilities.getJoinColumns(helper, annByType);
}
public JCTree getTree(Element element) {
Symbol symbol = (Symbol) element;
TypeSymbol enclosing = symbol.enclClass();
Env<AttrContext> env = enter.getEnv(enclosing);
if (env == null)
return null;
JCClassDecl classNode = env.enclClass;
if (classNode != null) {
if (TreeInfo.symbolFor(classNode) == element)
return classNode;
for (JCTree node : classNode.getMembers())
if (TreeInfo.symbolFor(node) == element)
return node;
}
return null;
}
private void addDirectValue(CodeBlock.Builder builder)
{
Element element = foundImplicit.getElement();
if ( element.getKind() == ElementKind.FIELD )
{
builder.add("$T.$L", element.getEnclosingElement().asType(), element.getSimpleName());
}
else
{
ExecutableElement method = (ExecutableElement)element;
AtomicBoolean isFirst = new AtomicBoolean(false);
CodeBlock methodCode = new ImplicitMethod(environment, method, implicitClassSpec, contextItems).build();
builder.add("$T.$L(", element.getEnclosingElement().asType(), element.getSimpleName());
builder.add(methodCode);
builder.add(")");
}
}
private static void parseBetweenValidation(
Element startElement,
Set<Element> parents,
List<ValidationField> fields
) {
boolean hasError = (
isInvalid(Between.Start.class, startElement) ||
isInaccessible(Between.Start.class, startElement)
) || (
isInvalid(Between.Limit.class, startElement) ||
isInaccessible(Between.Limit.class, startElement)
);
if (hasError) {
return;
}
Element limitElement = validateBetweenStartAnnotation(startElement);
if (limitElement == null) return;
parseBetweenStartValidation(startElement, parents, fields);
parseBetweenLimitValidation(limitElement, parents, fields);
}
/**
* Complete all analysis on the given classes.
* This can be used to ensure that all compile time errors are reported.
* The classes must have previously been returned from {@link #enter}.
* If null is specified, all outstanding classes will be analyzed.
*
* @param classes a list of class elements
*/
// This implementation requires that we open up privileges on JavaCompiler.
// An alternative implementation would be to move this code to JavaCompiler and
// wrap it here
public Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes) throws IOException {
enter(null); // ensure all classes have been entered
final ListBuffer<Element> results = new ListBuffer<Element>();
try {
if (classes == null) {
handleFlowResults(compiler.flow(compiler.attribute(compiler.todo)), results);
} else {
Filter f = new Filter() {
public void process(Env<AttrContext> env) {
handleFlowResults(compiler.flow(compiler.attribute(env)), results);
}
};
f.run(compiler.todo, classes);
}
} finally {
compiler.log.flush();
}
return results;
}
void validateEnclosingElement(Element element) {
TypeElement typeElement = ctx.getMoreElements().toTypeElement(element);
if (typeElement == null) {
return;
}
String simpleName = typeElement.getSimpleName().toString();
if (simpleName.contains(Constants.BINARY_NAME_DELIMITER)
|| simpleName.contains(Constants.TYPE_NAME_DELIMITER)) {
throw new AptException(
Message.DOMA4417, typeElement, new Object[] {typeElement.getQualifiedName()});
}
NestingKind nestingKind = typeElement.getNestingKind();
if (nestingKind == NestingKind.TOP_LEVEL) {
return;
} else if (nestingKind == NestingKind.MEMBER) {
Set<Modifier> modifiers = typeElement.getModifiers();
if (modifiers.containsAll(Arrays.asList(Modifier.STATIC, Modifier.PUBLIC))) {
validateEnclosingElement(typeElement.getEnclosingElement());
} else {
throw new AptException(
Message.DOMA4415, typeElement, new Object[] {typeElement.getQualifiedName()});
}
} else {
throw new AptException(
Message.DOMA4416, typeElement, new Object[] {typeElement.getQualifiedName()});
}
}
void testParseType(TypeElement clazz) {
DeclaredType type = (DeclaredType)task.parseType("List<String>", clazz);
for (Element member : elements.getAllMembers((TypeElement)type.asElement())) {
TypeMirror mt = types.asMemberOf(type, member);
System.out.format("type#%d: %s : %s -> %s%n",
numParseTypeElements, member.getSimpleName(), member.asType(), mt);
numParseTypeElements++;
}
}
@Override
public FileObject createResource(
JavaFileManager.Location location,
CharSequence pkg,
CharSequence relativeName,
Element... originatingElements)
throws IOException {
return delegate.createResource(location, pkg, relativeName, originatingElements);
}
private void processClass(final Element element) throws ScriptException,
FileNotFoundException {
for (final AnnotationMirror annotationMirror : element
.getAnnotationMirrors()) {
processAnnotation(annotationMirror);
}
}
@Override
public Void visitValue(ValueTree tree, Void ignore) {
ReferenceTree ref = tree.getReference();
if (ref == null || ref.getSignature().isEmpty()) {
if (!isConstant(env.currElement))
env.messages.error(REFERENCE, tree, "dc.value.not.allowed.here");
} else {
Element e = env.trees.getElement(new DocTreePath(getCurrentPath(), ref));
if (!isConstant(e))
env.messages.error(REFERENCE, tree, "dc.value.not.a.constant");
}
markEnclosingTag(Flag.HAS_INLINE_TAG);
return super.visitValue(tree, ignore);
}
private TypeElement getClassOf(Element e) {
Element t = e;
while (!(t instanceof TypeElement)) {
if (t == null) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Element " + e + " has no enclosing class");
return null;
}
t = t.getEnclosingElement();
}
return (TypeElement) t;
}
private void generateContentProviderIfRequested(final String packageName, final Set<? extends Element> entityAnnotated) throws Exception {
List<ContentProviderData> providers = new LinkedList<ContentProviderData>();
for (Element entity : entityAnnotated) {
Entity entityAnnotation = entity.getAnnotation(Entity.class);
if (entityAnnotation.contentProvider()) {
ContentProviderBuilder providerBuilder = new ContentProviderBuilder(packageName, entity, messager);
SourceContentProviderData providerData = providerBuilder.build();
JavaFileWriter javaFileWriter = new JavaFileWriter(packageName, providerData.getSimpleName(), processingEnv);
javaFileWriter.write(providerData.getSource());
providers.add(providerData);
}
}
androidManifestAccess.addProviders(providers);
}
/**
* 记录需要生成的类与属性
* @param elements elements集合
*/
private void categories(Set<? extends Element> elements) {
for (Element element : elements) {
//获得父节点 (类)
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
if (parentAndChild.containsKey(enclosingElement)) {
parentAndChild.get(enclosingElement).add(element);
} else {
List<Element> child = new ArrayList<>();
child.add(element);
parentAndChild.put(enclosingElement, child);
}
}
}
/**
* Tests getting a DocCommentTree from an element, as well
* as test if break iterator setter/getter works correctly.
*
* @param javaFileName a test file to be processed
* @param expected the expected output
* @throws java.io.IOException
*/
public void runElementAndBreakIteratorTests(String javaFileName, String expected) throws IOException {
List<File> javaFiles = new ArrayList<>();
javaFiles.add(new File(testSrc, javaFileName));
List<File> dirs = new ArrayList<>();
dirs.add(new File(testSrc));
try (StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null)) {
fm.setLocation(javax.tools.StandardLocation.SOURCE_PATH, dirs);
Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(javaFiles);
final JavacTask t = javac.getTask(null, fm, null, null, null, fos);
final DocTrees trees = DocTrees.instance(t);
Iterable<? extends Element> elements = t.analyze();
Element klass = elements.iterator().next();
DocCommentTree dcTree = trees.getDocCommentTree(klass);
List<? extends DocTree> firstSentence = dcTree.getFirstSentence();
StringWriter sw = new StringWriter();
DocPretty pretty = new DocPretty(sw);
pretty.print(firstSentence);
check("getDocCommentTree(Element)", expected, sw.toString());
BreakIterator bi = BreakIterator.getSentenceInstance(Locale.FRENCH);
trees.setBreakIterator(bi);
BreakIterator nbi = trees.getBreakIterator();
if (bi.equals(nbi)) {
pass++;
check("getDocCommentTree(Element) with BreakIterator", expected, sw.toString());
} else {
fail++;
System.err.println("BreakIterators don't match");
}
}
}
private void findEnabledProductions(Set<Element> productions )
{
/*
* This is partial implementation of the spec :
* A bean is said to be enabled if:
* - it is not a producer method or field of a disabled bean
* Full check for enabled/disabled bean is very complicated.
* Here is check only for enabled alternatives if any.
*/
for (Iterator<Element> iterator = productions.iterator();
iterator.hasNext(); )
{
Element element = iterator.next();
TypeElement enclosingTypeElement = getHelper().
getCompilationController().getElementUtilities().
enclosingTypeElement(element);
if ( getResult().isAlternative(enclosingTypeElement)){
String name = enclosingTypeElement.getQualifiedName().toString();
if ( getResult().hasAlternative(enclosingTypeElement) ){
if ( !getModel().getAlternativeClasses().contains( name ) ){
iterator.remove();
}
}
if ( !alternativeStereotypesEnabled(enclosingTypeElement) ){
iterator.remove();
}
}
}
}
@Override
protected boolean handleProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws LayerGenerationException {
for (Element element : roundEnv.getElementsAnnotatedWith(FunctionInterceptor.Registration.class)) {
layer(element)
.instanceFile(ModelExtender.FUNCTION_INTERCEPTORS_PATH, null, FunctionInterceptor.class)
.position(element.getAnnotation(FunctionInterceptor.Registration.class).priority())
.write();
}
return true;
}
@Override
public ImmutableSet<TypeVariable> visitDeclared(
DeclaredType t, Set<Element> visited) {
if (!visited.add(t.asElement())) {
return ImmutableSet.of();
}
ImmutableSet.Builder<TypeVariable> typeVariables = ImmutableSet.builder();
for (TypeMirror typeArgument : t.getTypeArguments()) {
typeVariables.addAll(typeArgument.accept(this, visited));
}
return typeVariables.build();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
final Set<? extends Element> submoduleDatabaseElements = roundEnv.getElementsAnnotatedWith(SubmoduleDatabase.class);
if (!parseSubmodules(submoduleDatabaseElements)) return false;
final Set<? extends Element> databaseElements = roundEnv.getElementsAnnotatedWith(Database.class);
if (!submoduleDatabaseElements.isEmpty() && !databaseElements.isEmpty()) {
environment.error("Module can have either @%s or @%s annotated element, but not both",
Database.class.getSimpleName(), SubmoduleDatabase.class.getSimpleName());
return false;
}
if (databaseElements.size() > 1) {
environment.error(ERR_SINGLE_DB_ALLOWED);
return false;
}
for (Element element : databaseElements) {
final Database database = element.getAnnotation(Database.class);
if (environment.getSubmoduleDatabases() == null) {
final List<Dual<TypeElement, String>> submodules = getSubmodules(environment, database);
if (!submodules.isEmpty()) {
environment.setSubmoduleDatabases(submodules);
}
} else {
environment.error(element, ERR_SINGLE_DB_ALLOWED);
return false;
}
final String dbName = database.name();
if (!Strings.isNullOrEmpty(dbName)) {
environment.setDbName("\"" + dbName + "\"");
}
final int version = database.version();
if (version >= 0 && !environment.isDebugVariant()) {
environment.setDbVersion(Integer.toString(version));
}
}
return true;
}
@TriggerPatterns({
@TriggerPattern(value = "java.lang.StringBuffer $x = $expr;"),
@TriggerPattern(value = "java.lang.StringBuilder $x = $expr;"),
})
public static ErrorDescription checkReplace(HintContext ctx) {
CompilationInfo ci = ctx.getInfo();
TreePath vp = ctx.getVariables().get("$x"); // NOI18N
TreePath initP = ctx.getVariables().get("$expr"); // NOI18N
Element el = ci.getTrees().getElement(vp);
if (el == null || el.getKind() != ElementKind.LOCAL_VARIABLE) {
return null;
}
StringBufferUsageScanner scanner = new StringBufferUsageScanner(ci, ((VariableElement)el));
TreePath declRoot = ctx.getPath().getParentPath();
scanner.scan(declRoot, null);
if (scanner.isIncompatible()) {
return null;
}
NewAppendScanner newScan = new NewAppendScanner(ci);
if (newScan.scan(initP, null) != Boolean.TRUE || !newScan.hasContents) {
return null;
}
return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), Bundle.TEXT_ReplaceStringBufferByString(),
new RewriteToStringFix(
TreePathHandle.create(vp, ci),
TreePathHandle.create(declRoot, ci)
).toEditorFix());
}