Java Code Examples for javax.lang.model.element.Element#getEnclosingElement()

The following examples show how to use javax.lang.model.element.Element#getEnclosingElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RelationRule.java    From alchemy with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Element element) throws Exception {
    final Element enclosingElement = element.getEnclosingElement();
    if (enclosingElement.getAnnotation(Entry.class) == null) {
        throw new ElementException("Class containing @Relation must be annotated with @Entry", enclosingElement);
    }
    element.asType().accept(new SimpleTypeVisitor7<Void, Void>() {
        @Override
        public Void visitDeclared(DeclaredType t, Void unused) {
            final List<? extends TypeMirror> args = t.getTypeArguments();
            if (args.isEmpty()) {
                processOneToOne(element, t.asElement());
            } else {
                processOneToMany(element, (TypeElement) t.asElement(), args.get(0));
            }
            return super.visitDeclared(t, unused);
        }
    }, null);
}
 
Example 2
Source File: LoggerNotStaticFinal.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value="$mods$ java.util.logging.Logger $LOG;"), //NOI18N
    @TriggerPattern(value="$mods$ java.util.logging.Logger $LOG = $init;") //NOI18N
})
public static ErrorDescription checkLoggerDeclaration(HintContext ctx) {
    Element e = ctx.getInfo().getTrees().getElement(ctx.getPath());
    if (e != null && e.getEnclosingElement().getKind() == ElementKind.CLASS &&
        (!e.getModifiers().contains(Modifier.STATIC) || !e.getModifiers().contains(Modifier.FINAL)) &&
        ctx.getInfo().getElementUtilities().outermostTypeElement(e) == e.getEnclosingElement()
    ) {
        return ErrorDescriptionFactory.forName(
                ctx,
                ctx.getPath(),
                NbBundle.getMessage(LoggerNotStaticFinal.class, "MSG_LoggerNotStaticFinal_checkLoggerDeclaration", e), //NOI18N
                new LoggerNotStaticFinalFix(NbBundle.getMessage(LoggerNotStaticFinal.class, "MSG_LoggerNotStaticFinal_checkLoggerDeclaration_fix", e), TreePathHandle.create(e, ctx.getInfo())).toEditorFix() //NOI18N
        );
    } else {
        return null;
    }
}
 
Example 3
Source File: ExtensionAnnotationProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 4
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public TypeElement getEnclosingTypeElement(Element e) {
    if (e.getKind() == ElementKind.PACKAGE)
        return null;
    Element encl = e.getEnclosingElement();
    ElementKind kind = encl.getKind();
    if (kind == ElementKind.PACKAGE)
        return null;
    while (!(kind.isClass() || kind.isInterface())) {
        encl = encl.getEnclosingElement();
    }
    return (TypeElement)encl;
}
 
Example 5
Source File: KratosProcessor.java    From Kratos with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void parseBindText(Element element, Map<TypeElement, BindingClass> targetClassMap,
                           Set<String> erasedTargetNames) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.TYPEVAR) {
        TypeVariable typeVariable = (TypeVariable) elementType;
        elementType = typeVariable.getUpperBound();
    }
    // Assemble information on the field.
    int[] ids = element.getAnnotation(BindText.class).value();
    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false);
    for (int id : ids) {
        if (bindingClass != null) {
            KBindings bindings = bindingClass.getKBindings(String.valueOf(id));
            if (bindings != null) {
                Iterator<FieldViewBinding> iterator = bindings.getFieldBindings().iterator();
                if (iterator.hasNext()) {
                    FieldViewBinding existingBinding = iterator.next();
                    error(element, "Attempt to use @%s for an already bound ID %s on '%s'. (%s.%s)",
                            BindText.class.getSimpleName(), id, existingBinding.getName(),
                            enclosingElement.getQualifiedName(), element.getSimpleName());
                    return;
                }
            }
        } else {
            bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false);
        }
        String name = element.getSimpleName().toString();
        TypeName type = TypeName.get(elementType);
        boolean required = isRequiredBinding(element);

        FieldViewBinding binding = new FieldViewBinding(name, type, required);
        bindingClass.addField(String.valueOf(id), binding);
    }

    // Add the type-erased version to the valid binding targets set.
    erasedTargetNames.add(enclosingElement.toString());
}
 
Example 6
Source File: ViewFinderProcesser.java    From ViewFinder with Apache License 2.0 5 votes vote down vote up
private AnnotatedClass getAnnotatedClass(Element element) {
    TypeElement classElement = (TypeElement) element.getEnclosingElement();
    String fullClassName = classElement.getQualifiedName().toString();
    AnnotatedClass annotatedClass = mAnnotatedClassMap.get(fullClassName);
    if (annotatedClass == null) {
        annotatedClass = new AnnotatedClass(classElement, mElementUtils);
        mAnnotatedClassMap.put(fullClassName, annotatedClass);
    }
    return annotatedClass;
}
 
Example 7
Source File: Checker.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private Element getEnclosingPackageOrClass(Element e) {
    while (e != null) {
        switch (e.getKind()) {
            case CLASS:
            case ENUM:
            case INTERFACE:
            case PACKAGE:
                return e;
            default:
                e = e.getEnclosingElement();
        }
    }
    return e;
}
 
Example 8
Source File: ProcessorContext.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
private String getRootClassOf(final Element e) {
	final ElementKind kind = e.getKind();
	final Element enclosing = e.getEnclosingElement();
	final ElementKind enclosingKind = enclosing.getKind();
	if ((kind == ElementKind.CLASS || kind == ElementKind.INTERFACE)
			&& !(enclosingKind == ElementKind.CLASS || enclosingKind == ElementKind.INTERFACE)) {
		return e.toString();
	}
	return getRootClassOf(enclosing);
}
 
Example 9
Source File: ButterKnifeProcessor.java    From butterknife with Apache License 2.0 5 votes vote down vote up
private void parseResourceInt(Element element,
    Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> erasedTargetNames) {
  boolean hasError = false;
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Verify that the target type is int.
  if (element.asType().getKind() != TypeKind.INT) {
    error(element, "@%s field type must be 'int'. (%s.%s)", BindInt.class.getSimpleName(),
        enclosingElement.getQualifiedName(), element.getSimpleName());
    hasError = true;
  }

  // Verify common generated code restrictions.
  hasError |= isInaccessibleViaGeneratedCode(BindInt.class, "fields", element);
  hasError |= isBindingInWrongPackage(BindInt.class, element);

  if (hasError) {
    return;
  }

  // Assemble information on the field.
  String name = element.getSimpleName().toString();
  int id = element.getAnnotation(BindInt.class).value();
  Id resourceId = elementToId(element, BindInt.class, id);
  BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
  builder.addResource(
      new FieldResourceBinding(resourceId, name, FieldResourceBinding.Type.INT));

  erasedTargetNames.add(enclosingElement);
}
 
Example 10
Source File: AnnotatedCommandSourceGenerator.java    From picocli with Apache License 2.0 5 votes vote down vote up
private static String extractPackageName(TypeElement typeElement) {
    Element enclosing = typeElement.getEnclosingElement();
    while (enclosing != null) {
        if (enclosing instanceof PackageElement) {
            PackageElement pkg = (PackageElement) enclosing;
            if (pkg.isUnnamed()) {
                return "";
            }
            String fqcn = pkg.getQualifiedName().toString();
            return fqcn;
        }
        enclosing = enclosing.getEnclosingElement();
    }
    return "";
}
 
Example 11
Source File: NoPrivateTypesExported.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private TypeElement outermostTypeElement(Element el) {
    while (el.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        el = el.getEnclosingElement();
    }

    return (TypeElement) el;
}
 
Example 12
Source File: LocalInAnonymous.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitMethod(MethodTree node, Void p) {
    Element prevOwner = currentOwner;
    try {
        Element currentElement = trees.getElement(getCurrentPath());
        if (currentElement.getEnclosingElement() != currentOwner) {
            throw new AssertionError("Unexpected owner!");
        }
        currentOwner = currentElement;
        return super.visitMethod(node, p);
    } finally {
        currentOwner = prevOwner;
    }
}
 
Example 13
Source File: AttributeFieldValidation.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv)
{
    Elements elementUtils = processingEnv.getElementUtils();
    Types typeUtils = processingEnv.getTypeUtils();

    TypeElement annotationElement = elementUtils.getTypeElement(MANAGED_ATTRIBUTE_FIELD_CLASS_NAME);
    for (Element e : roundEnv.getElementsAnnotatedWith(annotationElement))
    {
        for(AnnotationMirror am : e.getAnnotationMirrors())
        {
            if(typeUtils.isSameType(am.getAnnotationType(), annotationElement.asType()))
            {
                for(Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : am.getElementValues().entrySet())
                {
                    String elementName = entry.getKey().getSimpleName().toString();
                    if(elementName.equals("beforeSet") || elementName.equals("afterSet"))
                    {
                        String methodName = entry.getValue().getValue().toString();
                        if(!"".equals(methodName))
                        {
                            TypeElement parent = (TypeElement) e.getEnclosingElement();
                            if(!containsMethod(parent, methodName))
                            {
                                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                                                                         "Could not find method '"
                                                                         + methodName
                                                                         + "' which is defined as the "
                                                                         + elementName
                                                                         + " action", e);

                            }
                        }
                    }
                }
            }
        }
    }
    return false;
}
 
Example 14
Source File: FieldValidator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void run(CompilationController parameter) throws Exception {
    parameter.toPhase(JavaSource.Phase.RESOLVED);
    this.cinfo = parameter;
    if (targetHandle == null || srcHandle == null) {
        return;
    }
    TreePath srcPath = srcHandle.resolve(cinfo);
    if (srcPath == null) {
        return;
    }
    TreePath targetPath = targetHandle.resolve(cinfo);
    if (targetPath == null) {
        return;
    }
    initialScope = cinfo.getTrees().getScope(srcPath);
    Scope targetScope = cinfo.getTrees().getScope(targetPath);
    Map<? extends Element, Scope> visibleVariables = 
            cinfo.getElementUtilities().findElementsAndOrigins(initialScope, this);
    lastResult = null;
    Element target = cinfo.getTrees().getElement(targetPath);
    for (Element e : visibleVariables.keySet()) {
        switch (e.getKind()) {
            case FIELD: case ENUM_CONSTANT: case PARAMETER:
                Scope def = visibleVariables.get(e);
                if (def != targetScope) {
                    for (Scope s = def; s.getEnclosingClass() != null; s = s.getEnclosingScope()) {
                        if (s == target) {
                            lastResult = new MemberSearchResult(ElementHandle.create(e));
                            return;
                        }
                    }
                }
                TypeElement owner = def.getEnclosingClass();
                if (owner == null) {
                    // static import
                    lastResult = new MemberSearchResult(ElementHandle.create(e),
                        ElementHandle.create((TypeElement)e.getEnclosingElement()));
                } else if (owner == e.getEnclosingElement()) {
                    if (owner == target) {
                        lastResult = new MemberSearchResult(ElementHandle.create(e));
                        return;
                    } else {
                        lastResult = new MemberSearchResult(ElementHandle.create(e),
                            ElementHandle.create(owner));
                    }
                } else {
                    // special case - hiding superclass field
                    lastResult = new MemberSearchResult(ElementHandle.create(e),
                        ElementHandle.create(owner), null);
                }
                break;
            case EXCEPTION_PARAMETER:
            case LOCAL_VARIABLE: 
            case RESOURCE_VARIABLE: {
                TreePath locPath = findLocalPathWorkaround(cinfo, e, srcPath);
                if (locPath == null) {
                    lastResult = new MemberSearchResult(e.getKind());
                } else {
                    lastResult = new MemberSearchResult(TreePathHandle.create(locPath, cinfo), e.getKind());
                }
            }
                return;
            default:
                // another namespace
                return;
        }
    }
}
 
Example 15
Source File: OverridableMethodCallInConstructor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Tree.Kind.METHOD_INVOCATION)
public static ErrorDescription hint(HintContext ctx) {
    MethodInvocationTree mit = (MethodInvocationTree) ctx.getPath().getLeaf();
    CompilationInfo info = ctx.getInfo();
    TreePath enclosingMethod = Utilities.findOwningExecutable(ctx, ctx.getPath(), false);

    if (enclosingMethod == null) {
        return null;
    }

    Element enclosingMethodElement = ctx.getInfo().getTrees().getElement(enclosingMethod);
    
    if (enclosingMethodElement == null || enclosingMethodElement.getKind() != ElementKind.CONSTRUCTOR) {
        return null;
    }

    Element methodInvocationElement = info.getTrees().getElement(new TreePath(ctx.getPath(), mit.getMethodSelect()));
    if (methodInvocationElement == null || methodInvocationElement.getKind() != ElementKind.METHOD) {
        return null;
    }
    Element classElement = methodInvocationElement.getEnclosingElement();
    if (classElement == null || classElement.getKind() != ElementKind.CLASS) {
        return null;
    }
    Element classEl = enclosingMethodElement.getEnclosingElement();
    if (classEl == null || classEl.getKind() != ElementKind.CLASS) {
        return null;
    }
    boolean sameClass = classElement.equals(enclosingMethodElement.getEnclosingElement());
    if (!info.getTypes().isSubtype(classEl.asType(), classElement.asType())) {
        return null;
    }
    // classEl exts classElemenet - either classElement == classEl, or classElement cannot be final anyway
    if (classEl.getModifiers().contains(Modifier.FINAL)) {
        return null;
    }

    Set<Modifier> modifiers = methodInvocationElement.getModifiers();
    if (modifiers.contains(Modifier.PRIVATE) || 
        modifiers.contains(Modifier.FINAL) || 
        modifiers.contains(Modifier.STATIC)) {
        return null;
    }

    if (!invocationOnThis(mit)) {
        return null;
    }

    TreePath methodDeclaration = ctx.getInfo().getTrees().getPath(methodInvocationElement);

    if (methodDeclaration == null || ctx.getInfo().getTreeUtilities().isSynthetic(methodDeclaration)) return null;

    return ErrorDescriptionFactory.forName(ctx, mit,
            NbBundle.getMessage(
                OverridableMethodCallInConstructor.class,
                "MSG_org.netbeans.modules.java.hints.OverridableMethodCallInConstructor"),
                sameClass ? computeFixes((MethodTree) methodDeclaration.getLeaf(),
                    classElement, ctx) : null);
}
 
Example 16
Source File: FileUtils.java    From Witch-Android with Apache License 2.0 4 votes vote down vote up
private static String getElementPackage(Element element) {
    while (element.getKind() != PACKAGE) {
        element = element.getEnclosingElement();
    }
    return ((PackageElement) element).getQualifiedName().toString();
}
 
Example 17
Source File: DependencyRequest.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
static DeclaredType getEnclosingType(Element element) {
  while (!MoreElements.isType(element)) {
    element = element.getEnclosingElement();
  }
  return MoreTypes.asDeclared(element.asType());
}
 
Example 18
Source File: Main.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static PackageElement getPackage(TypeElement type) {
    Element owner = type;
    while (owner.getKind() != ElementKind.PACKAGE)
        owner = owner.getEnclosingElement();
    return (PackageElement)owner;
}
 
Example 19
Source File: PrintingProcessor.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
private void printModifiers(Element e) {
    ElementKind kind = e.getKind();
    if (kind == PARAMETER) {
        printAnnotationsInline(e);
    } else {
        printAnnotations(e);
        indent();
    }

    if (kind == ENUM_CONSTANT)
        return;

    Set<Modifier> modifiers = new LinkedHashSet<Modifier>();
    modifiers.addAll(e.getModifiers());

    switch (kind) {
    case ANNOTATION_TYPE:
    case INTERFACE:
        modifiers.remove(Modifier.ABSTRACT);
        break;

    case ENUM:
        modifiers.remove(Modifier.FINAL);
        modifiers.remove(Modifier.ABSTRACT);
        break;

    case METHOD:
    case FIELD:
        Element enclosingElement = e.getEnclosingElement();
        if (enclosingElement != null &&
            enclosingElement.getKind().isInterface()) {
            modifiers.remove(Modifier.PUBLIC);
            modifiers.remove(Modifier.ABSTRACT); // only for methods
            modifiers.remove(Modifier.STATIC);   // only for fields
            modifiers.remove(Modifier.FINAL);    // only for fields
        }
        break;

    }

    for(Modifier m: modifiers) {
        writer.print(m.toString() + " ");
    }
}
 
Example 20
Source File: Main.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static PackageElement getPackage(TypeElement type) {
    Element owner = type;
    while (owner.getKind() != ElementKind.PACKAGE)
        owner = owner.getEnclosingElement();
    return (PackageElement)owner;
}