Search in sources :

Example 81 with Element

use of javax.lang.model.element.Element in project androidannotations by androidannotations.

the class ModelExtractor method extractAncestorsAnnotations.

private void extractAncestorsAnnotations(AnnotationElementsHolder extractedModel, Set<String> annotationTypesToCheck, Set<TypeElement> rootTypeElements) {
    for (TypeElement rootTypeElement : rootTypeElements) {
        Set<TypeElement> ancestors = new LinkedHashSet<>();
        addAncestorsElements(ancestors, rootTypeElement);
        if (!ancestors.isEmpty()) {
            for (TypeElement ancestor : ancestors) {
                extractAnnotations(extractedModel, annotationTypesToCheck, rootTypeElement, ancestor);
                for (Element ancestorEnclosedElement : ancestor.getEnclosedElements()) {
                    ElementKind enclosedKind = ancestorEnclosedElement.getKind();
                    if (enclosedKind == ElementKind.FIELD || enclosedKind == ElementKind.METHOD) {
                        extractAnnotations(extractedModel, annotationTypesToCheck, rootTypeElement, ancestorEnclosedElement);
                    }
                }
            }
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ElementKind(javax.lang.model.element.ElementKind) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement)

Example 82 with Element

use of javax.lang.model.element.Element in project androidannotations by androidannotations.

the class ModelExtractor method addAncestorsElements.

/**
	 * Finds superclasses until reaching the Object class
	 */
private void addAncestorsElements(Set<TypeElement> elements, TypeElement typeElement) {
    TypeMirror ancestorTypeMirror = typeElement.getSuperclass();
    if (!isRootObjectClass(ancestorTypeMirror) && !isAndroidClass(ancestorTypeMirror) && ancestorTypeMirror instanceof DeclaredType) {
        DeclaredType ancestorDeclaredType = (DeclaredType) ancestorTypeMirror;
        Element ancestorElement = ancestorDeclaredType.asElement();
        if (ancestorElement instanceof TypeElement) {
            addAncestorsElements(elements, (TypeElement) ancestorElement);
            elements.add((TypeElement) ancestorElement);
        }
    }
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) DeclaredType(javax.lang.model.type.DeclaredType)

Example 83 with Element

use of javax.lang.model.element.Element in project camel by apache.

the class AnnotationProcessorHelper method findTypeElement.

public static TypeElement findTypeElement(ProcessingEnvironment processingEnv, RoundEnvironment roundEnv, String className) {
    if (isNullOrEmpty(className) || "java.lang.Object".equals(className)) {
        return null;
    }
    Set<? extends Element> rootElements = roundEnv.getRootElements();
    for (Element rootElement : rootElements) {
        if (rootElement instanceof TypeElement) {
            TypeElement typeElement = (TypeElement) rootElement;
            String aRootName = canonicalClassName(typeElement.getQualifiedName().toString());
            if (className.equals(aRootName)) {
                return typeElement;
            }
        }
    }
    // fallback using package name
    Elements elementUtils = processingEnv.getElementUtils();
    int idx = className.lastIndexOf('.');
    if (idx > 0) {
        String packageName = className.substring(0, idx);
        PackageElement pe = elementUtils.getPackageElement(packageName);
        if (pe != null) {
            List<? extends Element> enclosedElements = getEnclosedElements(pe);
            for (Element rootElement : enclosedElements) {
                if (rootElement instanceof TypeElement) {
                    TypeElement typeElement = (TypeElement) rootElement;
                    String aRootName = canonicalClassName(typeElement.getQualifiedName().toString());
                    if (className.equals(aRootName)) {
                        return typeElement;
                    }
                }
            }
        }
    }
    return null;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) PackageElement(javax.lang.model.element.PackageElement) Elements(javax.lang.model.util.Elements)

Example 84 with Element

use of javax.lang.model.element.Element in project dagger by square.

the class GraphAnalysisProcessor method processCompleteModule.

private Map<String, Binding<?>> processCompleteModule(TypeElement rootModule, boolean ignoreCompletenessErrors) {
    Map<String, TypeElement> allModules = new LinkedHashMap<String, TypeElement>();
    collectIncludesRecursively(rootModule, allModules, new LinkedList<String>());
    ArrayList<GraphAnalysisStaticInjection> staticInjections = new ArrayList<GraphAnalysisStaticInjection>();
    Linker.ErrorHandler errorHandler = ignoreCompletenessErrors ? Linker.ErrorHandler.NULL : new GraphAnalysisErrorHandler(processingEnv, rootModule.getQualifiedName().toString());
    Linker linker = new Linker(null, new GraphAnalysisLoader(processingEnv), errorHandler);
    // to make the linker happy.
    synchronized (linker) {
        BindingsGroup baseBindings = new BindingsGroup() {

            @Override
            public Binding<?> contributeSetBinding(String key, SetBinding<?> value) {
                return super.put(key, value);
            }
        };
        BindingsGroup overrideBindings = new BindingsGroup() {

            @Override
            public Binding<?> contributeSetBinding(String key, SetBinding<?> value) {
                throw new IllegalStateException("Module overrides cannot contribute set bindings.");
            }
        };
        for (TypeElement module : allModules.values()) {
            Map<String, Object> annotation = getAnnotation(Module.class, module);
            boolean overrides = (Boolean) annotation.get("overrides");
            boolean library = (Boolean) annotation.get("library");
            BindingsGroup addTo = overrides ? overrideBindings : baseBindings;
            // Gather the injectable types from the annotation.
            Set<String> injectsProvisionKeys = new LinkedHashSet<String>();
            for (Object injectableTypeObject : (Object[]) annotation.get("injects")) {
                TypeMirror injectableType = (TypeMirror) injectableTypeObject;
                String providerKey = GeneratorKeys.get(injectableType);
                injectsProvisionKeys.add(providerKey);
                String key = isInterface(injectableType) ? providerKey : GeneratorKeys.rawMembersKey(injectableType);
                linker.requestBinding(key, module.getQualifiedName().toString(), getClass().getClassLoader(), false, true);
            }
            // Gather the static injections.
            for (Object staticInjection : (Object[]) annotation.get("staticInjections")) {
                TypeMirror staticInjectionTypeMirror = (TypeMirror) staticInjection;
                Element element = processingEnv.getTypeUtils().asElement(staticInjectionTypeMirror);
                staticInjections.add(new GraphAnalysisStaticInjection(element));
            }
            // Gather the enclosed @Provides methods.
            for (Element enclosed : module.getEnclosedElements()) {
                Provides provides = enclosed.getAnnotation(Provides.class);
                if (provides == null) {
                    continue;
                }
                ExecutableElement providerMethod = (ExecutableElement) enclosed;
                String key = GeneratorKeys.get(providerMethod);
                ProvidesBinding<?> binding = new ProviderMethodBinding(key, providerMethod, library);
                Binding<?> previous = addTo.get(key);
                if (previous != null) {
                    if ((provides.type() == SET || provides.type() == SET_VALUES) && previous instanceof SetBinding) {
                    // No duplicate bindings error if both bindings are set bindings.
                    } else {
                        String message = "Duplicate bindings for " + key;
                        if (overrides) {
                            message += " in override module(s) - cannot override an override";
                        }
                        message += ":\n    " + previous.requiredBy + "\n    " + binding.requiredBy;
                        error(message, providerMethod);
                    }
                }
                switch(provides.type()) {
                    case UNIQUE:
                        if (injectsProvisionKeys.contains(binding.provideKey)) {
                            binding.setDependedOn(true);
                        }
                        try {
                            addTo.contributeProvidesBinding(key, binding);
                        } catch (IllegalStateException ise) {
                            throw new ModuleValidationException(ise.getMessage(), providerMethod);
                        }
                        break;
                    case SET:
                        String setKey = GeneratorKeys.getSetKey(providerMethod);
                        SetBinding.add(addTo, setKey, binding);
                        break;
                    case SET_VALUES:
                        SetBinding.add(addTo, key, binding);
                        break;
                    default:
                        throw new AssertionError("Unknown @Provides type " + provides.type());
                }
            }
        }
        linker.installBindings(baseBindings);
        linker.installBindings(overrideBindings);
        for (GraphAnalysisStaticInjection staticInjection : staticInjections) {
            staticInjection.attach(linker);
        }
        // errors if any dependencies are missing.
        return linker.linkAll();
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) TypeMirror(javax.lang.model.type.TypeMirror) BindingsGroup(dagger.internal.BindingsGroup) TypeElement(javax.lang.model.element.TypeElement) Linker(dagger.internal.Linker) Provides(dagger.Provides) FileObject(javax.tools.FileObject) SetBinding(dagger.internal.SetBinding)

Example 85 with Element

use of javax.lang.model.element.Element in project dagger by square.

the class InjectAdapterProcessor method createInjectedClass.

/**
   * @param injectedClassName the name of a class with an @Inject-annotated member.
   */
private InjectedClass createInjectedClass(String injectedClassName) {
    TypeElement type = processingEnv.getElementUtils().getTypeElement(injectedClassName);
    boolean isAbstract = type.getModifiers().contains(ABSTRACT);
    List<Element> staticFields = new ArrayList<Element>();
    ExecutableElement constructor = null;
    List<Element> fields = new ArrayList<Element>();
    for (Element member : type.getEnclosedElements()) {
        if (member.getAnnotation(Inject.class) == null) {
            continue;
        }
        switch(member.getKind()) {
            case FIELD:
                if (member.getModifiers().contains(STATIC)) {
                    staticFields.add(member);
                } else {
                    fields.add(member);
                }
                break;
            case CONSTRUCTOR:
                if (constructor != null) {
                    // TODO(tbroyer): pass annotation information
                    error("Too many injectable constructors on " + type.getQualifiedName(), member);
                } else if (isAbstract) {
                    // TODO(tbroyer): pass annotation information
                    error("Abstract class " + type.getQualifiedName() + " must not have an @Inject-annotated constructor.", member);
                }
                constructor = (ExecutableElement) member;
                break;
            default:
                // TODO(tbroyer): pass annotation information
                error("Cannot inject " + elementToString(member), member);
                break;
        }
    }
    if (constructor == null && !isAbstract) {
        constructor = getNoArgsConstructor(type);
        if (constructor != null && !isCallableConstructor(constructor)) {
            constructor = null;
        }
    }
    return new InjectedClass(type, staticFields, constructor, fields);
}
Also used : Inject(javax.inject.Inject) TypeElement(javax.lang.model.element.TypeElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList)

Aggregations

Element (javax.lang.model.element.Element)286 TypeElement (javax.lang.model.element.TypeElement)227 ExecutableElement (javax.lang.model.element.ExecutableElement)148 VariableElement (javax.lang.model.element.VariableElement)96 TypeMirror (javax.lang.model.type.TypeMirror)68 PackageElement (javax.lang.model.element.PackageElement)48 ArrayList (java.util.ArrayList)39 DeclaredType (javax.lang.model.type.DeclaredType)30 IOException (java.io.IOException)29 Map (java.util.Map)26 HashSet (java.util.HashSet)23 LinkedHashSet (java.util.LinkedHashSet)22 List (java.util.List)22 Set (java.util.Set)22 Test (org.junit.Test)21 ElementKind (javax.lang.model.element.ElementKind)20 AnnotationMirror (javax.lang.model.element.AnnotationMirror)19 Elements (javax.lang.model.util.Elements)18 HashMap (java.util.HashMap)16 LinkedHashMap (java.util.LinkedHashMap)15