Java Code Examples for javax.lang.model.element.TypeElement#getEnclosedElements()
The following examples show how to use
javax.lang.model.element.TypeElement#getEnclosedElements() .
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: CustomConfigAnnotationParser.java From aircon with MIT License | 6 votes |
@SuppressWarnings("unchecked") private <T> T getAttributeFromAnnotationClass(String attr) { final TypeElement annotationElement = (TypeElement) mAnnotationMirror.getAnnotationType() .asElement(); for (final Element enclosedElement : annotationElement.getEnclosedElements()) { if (enclosedElement instanceof ExecutableElement) { final ExecutableElement method = (ExecutableElement) enclosedElement; if (method.getSimpleName() .toString() .equals(attr)) { return (T) method.getDefaultValue() .getValue(); } } } return null; }
Example 2
Source File: ElementUtils.java From ngAndroid with Apache License 2.0 | 6 votes |
public TypeMirror getElementType(TypeElement model, String field){ TypeMirror typeMirror = null; String fieldName = field.toLowerCase(); for(Element f : model.getEnclosedElements()){ if(f instanceof ExecutableElement) { String fName = f.getSimpleName().toString().toLowerCase(); ExecutableElement exec = (ExecutableElement) f; if (fName.equals("set" + fieldName) && isSetter(f)) { TypeMirror setType = exec.getParameters().get(0).asType(); if (typeMirror != null) { checkMatch(model, field, typeMirror, setType); } typeMirror = setType; } else if (fName.equals("get" + fieldName) && isGetter(f)) { TypeMirror getType = exec.getReturnType(); if (typeMirror != null) { checkMatch(model, field, typeMirror, getType); } typeMirror = getType; } } } return typeMirror; }
Example 3
Source File: RulesEngine.java From netbeans with Apache License 2.0 | 6 votes |
@Override public Void visitTypeAsClass(TypeElement javaClass, ProblemContext ctx){ // apply class-level rules for (Rule<TypeElement> rule : getClassRules()){ if (ctx.isCancelled()){ break; } ErrorDescription problems[] = rule.execute(javaClass, ctx); if (problems != null){ for (ErrorDescription problem : problems){ if (problem != null){ problemsFound.add(problem); } } } } // visit all enclosed elements for (Element enclosedClass : javaClass.getEnclosedElements()){ enclosedClass.accept(this, ctx); } return null; }
Example 4
Source File: ElementsReader.java From buck with Apache License 2.0 | 6 votes |
private void addAllElements(Element rootElement, Map<Path, Element> elements) { if (rootElement.getKind() == ElementKind.PACKAGE) { PackageElement packageElement = (PackageElement) rootElement; if (!packageElement.getAnnotationMirrors().isEmpty()) { elements.put( getRelativePathToClass(packageElement.getQualifiedName() + ".package-info"), packageElement); } } if (!rootElement.getKind().isClass() && !rootElement.getKind().isInterface()) { return; } TypeElement typeElement = (TypeElement) rootElement; elements.put(getRelativePath(typeElement), typeElement); for (Element enclosed : typeElement.getEnclosedElements()) { addAllElements(enclosed, elements); } }
Example 5
Source File: ConfigFileGenerator.java From hadoop-ozone with Apache License 2.0 | 6 votes |
private void writeConfigAnnotations(ConfigGroup configGroup, ConfigFileAppender appender, TypeElement typeElement) { //check if any of the setters are annotated with @Config for (Element element : typeElement.getEnclosedElements()) { if (element.getKind() == ElementKind.FIELD) { if (element.getAnnotation(Config.class) != null) { //update the ozone-site-generated.xml Config configAnnotation = element.getAnnotation(Config.class); String key = configGroup.prefix() + "." + configAnnotation.key(); appender.addConfig(key, configAnnotation.defaultValue(), configAnnotation.description(), configAnnotation.tags()); } } } }
Example 6
Source File: TableElement.java From sqlitemagic with Apache License 2.0 | 5 votes |
private void collectImmutableObjectMetadataIfNeeded(Environment environment, TypeElement tableElement) { if (environment.hasAutoValueLib()) { immutable = tableElement.getAnnotation(environment.getAutoValueAnnotation()) != null; if (immutable) { final Class<? extends Annotation> builderAnnotation = environment.getAutoValueBuilderAnnotation(); for (Element e : tableElement.getEnclosedElements()) { if (e.getKind() == ElementKind.CLASS && e.getAnnotation(builderAnnotation) != null) { $builderElement = (TypeElement) e; break; } } } } }
Example 7
Source File: WorkingRangesMethodExtractor.java From litho with Apache License 2.0 | 5 votes |
@Nullable public static SpecMethodModel<EventMethod, Void> getRegisterMethod( TypeElement typeElement, List<Class<? extends Annotation>> permittedInterStageInputAnnotations, Messager messager) { for (Element enclosedElement : typeElement.getEnclosedElements()) { if (enclosedElement.getKind() != ElementKind.METHOD) { continue; } final ExecutableElement executableElement = (ExecutableElement) enclosedElement; final Annotation registerRangesAnnotation = enclosedElement.getAnnotation(OnRegisterRanges.class); if (registerRangesAnnotation != null) { final List<MethodParamModel> methodParams = getMethodParams( executableElement, messager, getPermittedMethodParamAnnotations(permittedInterStageInputAnnotations), permittedInterStageInputAnnotations, ImmutableList.of()); return SpecMethodModel.<EventMethod, Void>builder() .annotations(ImmutableList.of()) .modifiers(ImmutableList.copyOf(new ArrayList<>(executableElement.getModifiers()))) .name(executableElement.getSimpleName()) .returnTypeSpec(generateTypeSpec(executableElement.getReturnType())) .typeVariables(ImmutableList.copyOf(getTypeVariables(executableElement))) .methodParams(ImmutableList.copyOf(methodParams)) .representedObject(executableElement) .build(); } } return null; }
Example 8
Source File: CompilerTreeApiTest.java From buck with Apache License 2.0 | 5 votes |
protected VariableElement findField(String name, TypeElement typeElement) { for (Element element : typeElement.getEnclosedElements()) { if (element.getKind().isField() && element.getSimpleName().contentEquals(name)) { return (VariableElement) element; } } throw new IllegalArgumentException( String.format("No such field in %s: %s", typeElement.getQualifiedName(), name)); }
Example 9
Source File: LazyJavaCompletionItem.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected JavaCompletionItem getDelegate(CompilationInfo info, Scope scope, TypeElement te) { Elements elements = info.getElements(); Trees trees = info.getTrees(); if (te != null) { Element element = null; boolean multiVersion = false; for (Element e : te.getEnclosedElements()) { if ((e.getKind().isField() || e.getKind() == ElementKind.METHOD) && name.contentEquals(Utilities.isCaseSensitive() ? e.getSimpleName() : e.getSimpleName().toString().toLowerCase()) && e.getModifiers().contains(Modifier.STATIC) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(e)) && trees.isAccessible(scope, e, (DeclaredType) te.asType())) { if (element != null) { multiVersion = true; break; } element = e; } } if (element != null) { name = element.getSimpleName().toString(); return createStaticMemberItem(info, (DeclaredType) te.asType(), element, element.asType(), multiVersion, substitutionOffset, elements.isDeprecated(element), addSemicolon, getWhiteList()); } } return null; }
Example 10
Source File: InjectPresenterProcessor.java From Moxy with MIT License | 5 votes |
private static List<PresenterProviderMethod> collectPresenterProviders(TypeElement presentersContainer) { List<PresenterProviderMethod> providers = new ArrayList<>(); for (Element element : presentersContainer.getEnclosedElements()) { if (element.getKind() != ElementKind.METHOD) { continue; } final ExecutableElement providerMethod = (ExecutableElement) element; final AnnotationMirror annotation = Util.getAnnotation(element, PROVIDE_PRESENTER_ANNOTATION); if (annotation == null) { continue; } final String name = providerMethod.getSimpleName().toString(); final DeclaredType kind = ((DeclaredType) providerMethod.getReturnType()); String type = Util.getAnnotationValueAsString(annotation, "type"); String tag = Util.getAnnotationValueAsString(annotation, "tag"); String presenterId = Util.getAnnotationValueAsString(annotation, "presenterId"); providers.add(new PresenterProviderMethod(kind, name, type, tag, presenterId)); } return providers; }
Example 11
Source File: TreeBackedTypeElementTest.java From buck with Apache License 2.0 | 5 votes |
@Test public void testEnclosedClasses() throws IOException { compile(String.join(System.lineSeparator(), "class Foo {", " class Bar { }", "}")); TypeElement fooElement = elements.getTypeElement("Foo"); TypeElement barElement = elements.getTypeElement("Foo.Bar"); List<Element> enclosedElements = new ArrayList<>(fooElement.getEnclosedElements()); assertThat(enclosedElements, Matchers.hasItems(barElement)); assertSame(fooElement, barElement.getEnclosingElement()); }
Example 12
Source File: InvokingMessageProcessor.java From SmartEventBus with Apache License 2.0 | 5 votes |
private void process(RoundEnvironment roundEnvironment) { for (Element element : roundEnvironment.getElementsAnnotatedWith(InvokingEventsDefine.class)) { if (element.getKind() == ElementKind.CLASS) { TypeElement typeElement = (TypeElement) element; PackageElement packageElement = elements.getPackageOf(element); String originalPackageName = packageElement.getQualifiedName().toString(); String originalClassName = typeElement.getSimpleName().toString(); List<EventInfo> events = new ArrayList<>(); List<? extends Element> enclosedElements = typeElement.getEnclosedElements(); for (Element element1 : enclosedElements) { if (element1.getKind() == ElementKind.FIELD) { VariableElement variableElement = (VariableElement) element1; String variableName = variableElement.getSimpleName().toString(); Object variableValue = variableElement.getConstantValue(); String eventType = getEventType(element1); System.out.println(TAG + "variableName: " + variableName + " | variableValue: " + variableValue); EventInfo eventInfo = new EventInfo(); eventInfo.setName(variableName); if (variableValue instanceof String) { eventInfo.setValue((String) variableValue); } eventInfo.setType(eventType); events.add(eventInfo); } } generateEventInterfaceClass(events, originalPackageName, originalClassName); } } }
Example 13
Source File: PropDefaultsExtractor.java From litho with Apache License 2.0 | 5 votes |
/** Get the prop defaults from the given {@link TypeElement}. */ public static ImmutableList<PropDefaultModel> getPropDefaults(TypeElement typeElement) { final List<PropDefaultModel> propDefaults = new ArrayList<>(); final List<? extends Element> enclosedElements = typeElement.getEnclosedElements(); for (Element enclosedElement : enclosedElements) { propDefaults.addAll(extractFromField(enclosedElement)); propDefaults.addAll(extractFromMethod(enclosedElement)); } return ImmutableList.copyOf(propDefaults); }
Example 14
Source File: ProvisionBinding.java From dagger2-sample with Apache License 2.0 | 5 votes |
private Optional<DependencyRequest> membersInjectionRequest(DeclaredType type) { TypeElement typeElement = MoreElements.asType(type.asElement()); if (!types.isSameType(elements.getTypeElement(Object.class.getCanonicalName()).asType(), typeElement.getSuperclass())) { return Optional.of(dependencyRequestFactory.forMembersInjectedType(type)); } for (Element enclosedElement : typeElement.getEnclosedElements()) { if (MEMBER_KINDS.contains(enclosedElement.getKind()) && (isAnnotationPresent(enclosedElement, Inject.class))) { return Optional.of(dependencyRequestFactory.forMembersInjectedType(type)); } } return Optional.absent(); }
Example 15
Source File: AddWsOperationHelper.java From netbeans with Apache License 2.0 | 5 votes |
private List<ExecutableElement> getMethods(CompilationController controller, TypeElement classElement) throws IOException { List<? extends Element> members = classElement.getEnclosedElements(); List<ExecutableElement> methods = ElementFilter.methodsIn(members); List<ExecutableElement> publicMethods = new ArrayList<ExecutableElement>(); for (ExecutableElement m:methods) { //Set<Modifier> modifiers = method.getModifiers(); //if (modifiers.contains(Modifier.PUBLIC)) { publicMethods.add(m); //} } return publicMethods; }
Example 16
Source File: ReactModuleSpecProcessor.java From react-native-GPay with MIT License | 4 votes |
private CodeBlock getCodeBlockForReactModuleInfos(List<String> nativeModules) throws ReactModuleSpecException { CodeBlock.Builder builder = CodeBlock.builder(); if (nativeModules == null || nativeModules.isEmpty()) { builder.addStatement("return $T.emptyMap()", COLLECTIONS_TYPE); } else { builder.addStatement("$T map = new $T()", MAP_TYPE, INSTANTIATED_MAP_TYPE); TypeMirror cxxModuleWrapperTypeMirror = mElements.getTypeElement(CxxModuleWrapper.class.getName()).asType(); for (String nativeModule : nativeModules) { String keyString = nativeModule; TypeElement typeElement = mElements.getTypeElement(nativeModule); if (typeElement == null) { throw new ReactModuleSpecException( keyString + " not found by ReactModuleSpecProcessor. " + "Did you misspell the module?"); } ReactModule reactModule = typeElement.getAnnotation(ReactModule.class); if (reactModule == null) { throw new ReactModuleSpecException( keyString + " not found by ReactModuleSpecProcessor. " + "Did you forget to add the @ReactModule annotation to the native module?"); } List<? extends Element> elements = typeElement.getEnclosedElements(); boolean hasConstants = false; if (elements != null) { hasConstants = elements .stream() .filter(element -> element.getKind() == ElementKind.METHOD) .map(Element::getSimpleName) .anyMatch( name -> name.contentEquals("getConstants") || name.contentEquals("getTypedExportedConstants")); } boolean isCxxModule = mTypes.isAssignable(typeElement.asType(), cxxModuleWrapperTypeMirror); String valueString = new StringBuilder() .append("new ReactModuleInfo(") .append("\"").append(reactModule.name()).append("\"").append(", ") .append(reactModule.canOverrideExistingModule()).append(", ") .append(reactModule.needsEagerInit()).append(", ") .append(hasConstants).append(", ") .append(isCxxModule) .append(")") .toString(); builder.addStatement("map.put(\"" + keyString + "\", " + valueString + ")"); } builder.addStatement("return map"); } return builder.build(); }
Example 17
Source File: Encodings.java From immutables with Apache License 2.0 | 4 votes |
Encoding(TypeElement type) { this.typeEncoding = type; if (type.getKind() != ElementKind.CLASS || type.getNestingKind() != NestingKind.TOP_LEVEL) { reporter.withElement(type).error("Encoding type '%s' should be top-level class", type.getSimpleName()); } this.$$package = processing().getElementUtils().getPackageOf(type).getQualifiedName().toString(); this.name = type.getSimpleName().toString(); CharSequence source = SourceExtraction.extract(processing(), type); if (source.length() == 0) { reporter.withElement(type) .error("No source code can be extracted for @Encoding class. Unsupported compilation mode"); } this.imports = SourceExtraction.importsFrom(source); this.sourceMapper = new SourceMapper(source); this.typesReader = new TypeExtractor(types, type); this.encodingSelfType = typesReader.get(type.asType()); addTypeParameters(type); for (Element e : type.getEnclosedElements()) { processMember(e); } if (postValidate()) { provideSyntheticElements(); } this.allElements = Iterables.concat( Arrays.asList( Iterables.filter( Arrays.asList( impl, from, toString, hashCode, equals, build, isInit), Predicates.notNull()), fields, expose, copy, helpers, builderFields, builderHelpers, builderInits)); this.linkage = new Linkage(); this.generatedImports = generatedImports(); }
Example 18
Source File: BindDynamicValuesMethodExtractor.java From litho with Apache License 2.0 | 4 votes |
/** Get the delegate methods from the given {@link TypeElement}. */ public static ImmutableList<SpecMethodModel<BindDynamicValueMethod, Void>> getOnBindDynamicValuesMethods(TypeElement typeElement, Messager messager) { final List<SpecMethodModel<BindDynamicValueMethod, Void>> methods = new ArrayList<>(); for (Element enclosedElement : typeElement.getEnclosedElements()) { if (enclosedElement.getKind() != ElementKind.METHOD) { continue; } final Annotation annotation = enclosedElement.getAnnotation(OnBindDynamicValue.class); if (annotation == null) { continue; } final ExecutableElement method = (ExecutableElement) enclosedElement; final List<MethodParamModel> methodParams = getMethodParams( method, messager, Collections.singletonList(Prop.class), Collections.emptyList(), Collections.emptyList()); final SpecMethodModel<BindDynamicValueMethod, Void> methodModel = SpecMethodModel.<BindDynamicValueMethod, Void>builder() .annotations(ImmutableList.of(annotation)) .modifiers(copyOf(new ArrayList<>(method.getModifiers()))) .name(method.getSimpleName()) .returnTypeSpec(generateTypeSpec(method.getReturnType())) .typeVariables(ImmutableList.of()) .methodParams(copyOf(methodParams)) .representedObject(method) .typeModel(null) .build(); methods.add(methodModel); } return ImmutableList.copyOf(methods); }
Example 19
Source File: EventMethodExtractor.java From litho with Apache License 2.0 | 4 votes |
/** Get the delegate methods from the given {@link TypeElement}. */ public static ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>> getOnEventMethods( Elements elements, TypeElement typeElement, List<Class<? extends Annotation>> permittedInterStageInputAnnotations, Messager messager, EnumSet<RunMode> runMode) { final List<SpecMethodModel<EventMethod, EventDeclarationModel>> delegateMethods = new ArrayList<>(); for (Element enclosedElement : typeElement.getEnclosedElements()) { if (enclosedElement.getKind() != ElementKind.METHOD) { continue; } final OnEvent onEventAnnotation = enclosedElement.getAnnotation(OnEvent.class); if (onEventAnnotation != null) { final ExecutableElement executableElement = (ExecutableElement) enclosedElement; final List<MethodParamModel> methodParams = getMethodParams( executableElement, messager, getPermittedMethodParamAnnotations(permittedInterStageInputAnnotations), permittedInterStageInputAnnotations, ImmutableList.<Class<? extends Annotation>>of()); final DeclaredType eventClassDeclaredType = ProcessorUtils.getAnnotationParameter( elements, executableElement, OnEvent.class, "value", DeclaredType.class); final Element eventClass = eventClassDeclaredType.asElement(); // In full mode, we get the return type from the Event class so that we can verify that it // matches the return type of the method. In ABI mode, we can't access the Event class so // we just use the method return type and leave validation for the full build. final TypeName returnType = runMode.contains(RunMode.ABI) ? TypeName.get(executableElement.getReturnType()) : EventDeclarationsExtractor.getReturnType(elements, eventClass); final ImmutableList<FieldModel> fields = runMode.contains(RunMode.ABI) ? ImmutableList.of() : FieldsExtractor.extractFields(eventClass); final SpecMethodModel<EventMethod, EventDeclarationModel> eventMethod = SpecMethodModel.<EventMethod, EventDeclarationModel>builder() .annotations(ImmutableList.of()) .modifiers(ImmutableList.copyOf(new ArrayList<>(executableElement.getModifiers()))) .name(executableElement.getSimpleName()) .returnTypeSpec(generateTypeSpec(executableElement.getReturnType())) .typeVariables(ImmutableList.copyOf(getTypeVariables(executableElement))) .methodParams(ImmutableList.copyOf(methodParams)) .representedObject(executableElement) .typeModel( new EventDeclarationModel( ClassName.bestGuess(eventClass.toString()), returnType, fields, eventClass)) .build(); delegateMethods.add(eventMethod); } } return ImmutableList.copyOf(delegateMethods); }
Example 20
Source File: AnnotationScanner.java From netbeans with Apache License 2.0 | 4 votes |
/** * Finds all elements annotated with the given annotation. This methods gets * the name of the searched annotation and an instance of the * {@link ElementAnnotationHandler} interface which will be used to * pass the found annotation elements back to the caller. * <p> * For finding annotated types {@link #TYPE_KINDS TYPE_KINDS} constant can be useful. * * @param searchedTypeName the fully-qualified name of the annotation * to be searched for. Cannot be <code>null</code>. * @param kinds the set of kinds to be searched for. * Cannot be neither <code>null</code> nor empty. * @param handler a {@link ElementAnnotationHandler}. Its <code>elementAnnotation</code> * method will be invoked once for each element annotated with the annotation * passed in the <code>searchedTypeName</code> parameter, with * the <code>element</code> parameter set to the annotated element, and the * <code>annotation</code> parameter set to an {@link AnnotationMirror} * (of type <code>searchedTypeName</code>) which that type is annotated with. * Cannot be null. * @param includeDerived include derived types into result ( * if annotation has @Inherited annotation ) or not * @throws InterruptedException when the search was interrupted (for * example because {@link org.netbeans.api.java.source.ClassIndex#getElements} * was interrupted). */ public void findAnnotations(final String searchedTypeName, Set<ElementKind> kinds, final AnnotationHandler handler, boolean includeDerived) throws InterruptedException { Parameters.notNull("searchedTypeName", searchedTypeName); // NOI18N Parameters.notNull("kinds", kinds); // NOI18N Parameters.notNull("handler", handler); // NOI18N LOGGER.log(Level.FINE, "findAnnotations called with {0} for {1}", new Object[] { searchedTypeName, kinds }); // NOI18N if (kinds.isEmpty()) { LOGGER.log(Level.WARNING, "findAnnotations: no kinds given"); // NOI18N return; } CompilationInfo controller = getHelper().getCompilationInfo(); TypeElement searchedType = controller.getElements().getTypeElement(searchedTypeName); if (searchedType == null) { LOGGER.log(Level.FINE, "findAnnotations: could not find type {0}", searchedTypeName); // NOI18N return; } ElementHandle<TypeElement> searchedTypeHandle = ElementHandle.create(searchedType); final Set<ElementHandle<TypeElement>> elementHandles = getHelper(). getCompilationInfo().getClasspathInfo().getClassIndex().getElements( searchedTypeHandle, EnumSet.of(SearchKind.TYPE_REFERENCES), EnumSet.of(SearchScope.SOURCE, SearchScope.DEPENDENCIES)); if (elementHandles == null) { throw new InterruptedException("ClassIndex.getElements() was interrupted"); // NOI18N } Set<ElementKind> nonTypeKinds = EnumSet.copyOf(kinds); nonTypeKinds.removeAll(TYPE_KINDS); Set<ElementKind> typeKinds = EnumSet.copyOf(kinds); typeKinds.retainAll(TYPE_KINDS); boolean followDerived = includeDerived || checkInheritance( searchedType ); if ( followDerived ){ followDerived = typeKinds.size() >0 ; } for (ElementHandle<TypeElement> elementHandle : elementHandles) { LOGGER.log(Level.FINE, "found element {0}", elementHandle.getQualifiedName()); // NOI18N TypeElement typeElement = elementHandle.resolve(controller); if (typeElement == null) { continue; } // class etc. if (!typeKinds.isEmpty()) { handleAnnotation(handler, typeElement, typeElement, searchedTypeName, typeKinds, followDerived); } // methods & fields if (!nonTypeKinds.isEmpty()) { for (Element element : typeElement.getEnclosedElements()) { if (nonTypeKinds.contains(element.getKind())) { handleAnnotation(handler, typeElement, element, searchedTypeName, nonTypeKinds, false); } } } } }