Java Code Examples for javax.lang.model.util.ElementFilter#constructorsIn()
The following examples show how to use
javax.lang.model.util.ElementFilter#constructorsIn() .
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: EntityClassInfo.java From netbeans with Apache License 2.0 | 6 votes |
private void initTypeElement(TypeMirror type, CompilationController controller){ DeclaredType declType = (DeclaredType) type; Element typeElement = declType.asElement(); List<ExecutableElement> constructors = ElementFilter. constructorsIn(typeElement.getEnclosedElements()); for (ExecutableElement constructor : constructors) { List<? extends VariableElement> parameters = constructor.getParameters(); if ( parameters.size()==0){ hasEmptyCtor = true; } else if (parameters.size()==1){ if ( hasSingleStringParam(constructor)){ stringConverter = StringConverter.CTOR; } } } if ( stringConverter == null ){ setStringConverter(typeElement); } if ( typeElement instanceof TypeElement ){ stringConverterClassName = ((TypeElement)typeElement). getQualifiedName().toString(); } }
Example 2
Source File: InternalDomainMetaFactory.java From doma with Apache License 2.0 | 6 votes |
void validateConstructor(TypeElement classElement, DomainMeta domainMeta) { for (ExecutableElement constructor : ElementFilter.constructorsIn(classElement.getEnclosedElements())) { if (constructor.getModifiers().contains(Modifier.PRIVATE)) { continue; } List<? extends VariableElement> parameters = constructor.getParameters(); if (parameters.size() != 1) { continue; } TypeMirror parameterType = ctx.getMoreTypes().erasure(parameters.get(0).asType()); if (ctx.getMoreTypes().isSameTypeWithErasure(parameterType, domainMeta.getValueType())) { return; } } throw new AptException( Message.DOMA4103, classElement, new Object[] {domainMeta.getValueType()}); }
Example 3
Source File: Constitution.java From immutables with Apache License 2.0 | 6 votes |
private boolean hasAccessibleConstructor(Element type) { List<ExecutableElement> constructors = ElementFilter.constructorsIn(type.getEnclosedElements()); if (constructors.isEmpty()) { // It is unclear (not checked) if we will have syntethic no-arg constructor // included, so we will assume no constructor to equate having a single constructors. return true; } for (ExecutableElement c : constructors) { if (c.getParameters().isEmpty()) { return !Visibility.of(c).isPrivate(); } } return false; }
Example 4
Source File: NodeIntrinsicVerifier.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
private ExecutableElement findConstructor(TypeElement nodeClass, TypeMirror[] signature, ExecutableElement intrinsicMethod, AnnotationMirror intrinsicAnnotation) { List<ExecutableElement> constructors = ElementFilter.constructorsIn(nodeClass.getEnclosedElements()); List<String> failureReasons = new ArrayList<>(); for (ExecutableElement constructor : constructors) { String failureReason = matchSignature(0, constructor, signature); if (failureReason == null) { // found return constructor; } failureReasons.add(failureReason); } // not found if (failureReasons.isEmpty()) { env.getMessager().printMessage(Kind.ERROR, "Could not find matching constructor for node intrinsic.", intrinsicMethod, intrinsicAnnotation); } else { for (String reason : failureReasons) { env.getMessager().printMessage(Kind.ERROR, reason, intrinsicMethod, intrinsicAnnotation); } } return null; }
Example 5
Source File: AbstractTestGenerator.java From netbeans with Apache License 2.0 | 6 votes |
/** */ protected boolean hasAccessibleNoArgConstructor(TypeElement srcClass) { boolean answer; List<ExecutableElement> constructors = ElementFilter.constructorsIn(srcClass.getEnclosedElements()); if (constructors.isEmpty()) { answer = true; //no explicit constructor -> synthetic no-arg. constructor } else { answer = false; for (ExecutableElement constructor : constructors) { if (constructor.getParameters().isEmpty()) { answer = !constructor.getModifiers().contains(Modifier.PRIVATE); break; } } } return answer; }
Example 6
Source File: CtorsAnalyzer.java From netbeans with Apache License 2.0 | 6 votes |
@Override public void analyze( TypeElement element, TypeElement parent, AtomicBoolean cancel, CdiAnalysisResult result ) { List<ExecutableElement> constructors = ElementFilter.constructorsIn( element.getEnclosedElements()); int injectCtorCount = 0; for (ExecutableElement ctor : constructors) { if ( cancel.get() ){ return; } if ( AnnotationUtil.hasAnnotation( ctor , AnnotationUtil.INJECT_FQN, result.getInfo())) { result.requireCdiEnabled( ctor ); injectCtorCount++; } } if ( injectCtorCount > 1){ result.addError( element, NbBundle.getMessage( CtorsAnalyzer.class, "ERR_InjectedCtor")); } }
Example 7
Source File: InjectBindingRegistry.java From dagger2-sample with Apache License 2.0 | 5 votes |
Optional<ProvisionBinding> getOrFindProvisionBinding(Key key) { checkNotNull(key); if (!key.isValidImplicitProvisionKey(types)) { return Optional.absent(); } ProvisionBinding binding = provisionBindings.getBinding(key); if (binding != null) { return Optional.of(binding); } // ok, let's see if we can find an @Inject constructor TypeElement element = MoreElements.asType(types.asElement(key.type())); List<ExecutableElement> constructors = ElementFilter.constructorsIn(element.getEnclosedElements()); ImmutableSet<ExecutableElement> injectConstructors = FluentIterable.from(constructors) .filter(new Predicate<ExecutableElement>() { @Override public boolean apply(ExecutableElement input) { return isAnnotationPresent(input, Inject.class); } }).toSet(); switch (injectConstructors.size()) { case 0: // No constructor found. return Optional.absent(); case 1: ProvisionBinding constructorBinding = provisionBindingFactory.forInjectConstructor( Iterables.getOnlyElement(injectConstructors), Optional.of(key.type())); return Optional.of(registerBinding(constructorBinding, false)); default: throw new IllegalStateException("Found multiple @Inject constructors: " + injectConstructors); } }
Example 8
Source File: MoreElements.java From doma with Apache License 2.0 | 5 votes |
public ExecutableElement getNoArgConstructor(TypeElement typeElement) { assertNotNull(typeElement); for (ExecutableElement constructor : ElementFilter.constructorsIn(typeElement.getEnclosedElements())) { if (constructor.getParameters().isEmpty()) { return constructor; } } return null; }
Example 9
Source File: ThrowForInvalidImmutableState.java From immutables with Apache License 2.0 | 5 votes |
private static boolean hasStringArrayConstructor(TypeElement element) { for (ExecutableElement e : ElementFilter.constructorsIn(element.getEnclosedElements())) { if (e.getModifiers().contains(Modifier.PUBLIC) && e.getParameters().size() == 1) { if (isArrayOfStrings(e.getParameters().get(0).asType())) { return true; } } } return false; }
Example 10
Source File: AbstractTestGenerator.java From netbeans with Apache License 2.0 | 5 votes |
/** * Finds an non-private constructor in the given class. * It tries to find the following types of constructors, in this order: * <ol> * <li>no-arg constructor</li> * <li>one-argument constructor without throws-clause</li> * <li>one-argument constructor with a throws-clause</li> * <li>two-argument constructor without throws-clause</li> * <li>two-argument constructor with a throws-clause</li> * <li>etc.</li> * </ol> * * @param clazz class to find constructor in * @return accessible (non-private) constructor, * or {@code null} if none was found */ private static ExecutableElement findAccessibleConstructor(TypeElement clazz) { List<ExecutableElement> ctors = ElementFilter.constructorsIn(clazz.getEnclosedElements()); if (ctors.isEmpty()) { return null; } ExecutableElement best = null; int bestArgsCount = -1; boolean bestHasThrown = false; for (ExecutableElement ctor : ctors) { if (ctor.getModifiers().contains(PRIVATE)) { continue; } List args = ctor.getParameters(); if (args.isEmpty()) { return ctor; //this is the best constructor we could find } int argsCount = args.size(); boolean hasThrown = !ctor.getThrownTypes().isEmpty(); if ((best == null) || (argsCount < bestArgsCount) || (argsCount == bestArgsCount) && bestHasThrown && !hasThrown) { best = ctor; bestArgsCount = argsCount; bestHasThrown = hasThrown; } } return best; }
Example 11
Source File: JavaSourceHelper.java From netbeans with Apache License 2.0 | 5 votes |
public static MethodTree getDefaultConstructor(CompilationController controller) { TypeElement classElement = getTopLevelClassElement(controller); List<ExecutableElement> constructors = ElementFilter.constructorsIn(classElement.getEnclosedElements()); for (ExecutableElement constructor : constructors) { if (constructor.getParameters().size() == 0) { return controller.getTrees().getTree(constructor); } } return null; }
Example 12
Source File: Analysis.java From dsl-json with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Nullable public ExecutableElement findAnnotatedConstructor(Element element, DeclaredType discoveredBy) { if (element.getKind() == ElementKind.INTERFACE || element.getKind() == ElementKind.ENUM || element.getKind() == ElementKind.CLASS && element.getModifiers().contains(Modifier.ABSTRACT)) { return null; } for (ExecutableElement constructor : ElementFilter.constructorsIn(element.getEnclosedElements())) { AnnotationMirror discAnn = getAnnotation(constructor, discoveredBy); if (discAnn != null) { if (constructor.getModifiers().contains(Modifier.PRIVATE) || constructor.getModifiers().contains(Modifier.PROTECTED) || requiresPublic(element) && !constructor.getModifiers().contains(Modifier.PUBLIC)) { hasError = true; messager.printMessage( Diagnostic.Kind.ERROR, "Constructor in '" + element.asType() + "' is annotated with " + discoveredBy + ", but it's not accessible.", constructor, discAnn); } return constructor; } for (AnnotationMirror ann : constructor.getAnnotationMirrors()) { if (alternativeCreators.contains(ann.getAnnotationType().toString())) { if (constructor.getModifiers().contains(Modifier.PRIVATE) || constructor.getModifiers().contains(Modifier.PROTECTED) || requiresPublic(element) && !constructor.getModifiers().contains(Modifier.PUBLIC)) { hasError = true; messager.printMessage( Diagnostic.Kind.ERROR, "Constructor in '" + element.asType() + "' is annotated with " + ann.getAnnotationType() + ", but it's not public.", constructor, ann); } return constructor; } } } return null; }
Example 13
Source File: JavaSourceHelper.java From netbeans with Apache License 2.0 | 5 votes |
public static ExecutableElement getLongestContructor(TypeElement typeElement) { List<ExecutableElement> constructors = ElementFilter.constructorsIn(typeElement.getEnclosedElements()); int max = -1; ExecutableElement current = null; for (ExecutableElement constructor : constructors) { if (constructor.getParameters().size() > max) { max = constructor.getParameters().size(); current = constructor; } } return current; }
Example 14
Source File: JavaSourceHelper.java From netbeans with Apache License 2.0 | 5 votes |
public static MethodTree getDefaultConstructor(CompilationController controller) { TypeElement classElement = getTopLevelClassElement(controller); if (classElement == null ) { return null; } List<ExecutableElement> constructors = ElementFilter.constructorsIn(classElement.getEnclosedElements()); for (ExecutableElement constructor : constructors) { if (constructor.getParameters().size() == 0) { return controller.getTrees().getTree(constructor); } } return null; }
Example 15
Source File: WebServiceVisitor.java From hottub with GNU General Public License v2.0 | 4 votes |
protected boolean isLegalImplementation(WebService webService, TypeElement classElement) { boolean isStateful = isStateful(classElement); Collection<Modifier> modifiers = classElement.getModifiers(); if (!modifiers.contains(Modifier.PUBLIC)) { builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_NOT_PUBLIC(classElement.getQualifiedName()), classElement); return false; } if (modifiers.contains(Modifier.FINAL) && !isStateful) { builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_IS_FINAL(classElement.getQualifiedName()), classElement); return false; } if (modifiers.contains(Modifier.ABSTRACT) && !isStateful) { builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_IS_ABSTRACT(classElement.getQualifiedName()), classElement); return false; } boolean hasDefaultConstructor = false; for (ExecutableElement constructor : ElementFilter.constructorsIn(classElement.getEnclosedElements())) { if (constructor.getModifiers().contains(Modifier.PUBLIC) && constructor.getParameters().isEmpty()) { hasDefaultConstructor = true; break; } } if (!hasDefaultConstructor && !isStateful) { if (classElement.getEnclosingElement() != null && !modifiers.contains(Modifier.STATIC)) { builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_IS_INNERCLASS_NOT_STATIC( classElement.getQualifiedName()), classElement); return false; } builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_NO_DEFAULT_CONSTRUCTOR( classElement.getQualifiedName()), classElement); return false; } if (webService.endpointInterface().isEmpty()) { if (!methodsAreLegal(classElement)) return false; } else { TypeElement interfaceElement = getEndpointInterfaceElement(webService.endpointInterface(), classElement); if (!classImplementsSei(classElement, interfaceElement)) return false; } return true; }
Example 16
Source File: ConvertorProcessor.java From netbeans with Apache License 2.0 | 4 votes |
private String instantiableClassOrMethod(Element e, boolean checkMethods, Annotation r) throws IllegalArgumentException, LayerGenerationException { switch (e.getKind()) { case CLASS: { String clazz = processingEnv.getElementUtils().getBinaryName((TypeElement) e).toString(); if (e.getModifiers().contains(Modifier.ABSTRACT)) { throw new LayerGenerationException(clazz + " must not be abstract", e, processingEnv, r); } { boolean hasDefaultCtor = false; for (ExecutableElement constructor : ElementFilter.constructorsIn(e.getEnclosedElements())) { if (constructor.getParameters().isEmpty()) { hasDefaultCtor = true; break; } } if (!hasDefaultCtor) { throw new LayerGenerationException(clazz + " must have a no-argument constructor", e, processingEnv, r); } } if (checkMethods) { TypeMirror propType; propType = processingEnv.getElementUtils().getTypeElement("java.util.Properties").asType(); boolean hasRead = false; boolean hasWrite = false; for (ExecutableElement m : ElementFilter.methodsIn(e.getEnclosedElements())) { if ( m.getParameters().size() == 1 && m.getSimpleName().contentEquals("readProperties") && m.getParameters().get(0).asType().equals(propType) ) { hasRead = true; } if ( m.getParameters().size() == 1 && m.getSimpleName().contentEquals("writeProperties") && m.getParameters().get(0).asType().equals(propType) && m.getReturnType().getKind() == TypeKind.VOID ) { hasWrite = true; } } if (!hasRead) { throw new LayerGenerationException(clazz + " must have proper readProperties method", e, processingEnv, r); } if (!hasWrite) { throw new LayerGenerationException(clazz + " must have proper writeProperties method", e, processingEnv, r); } } return clazz; } default: throw new LayerGenerationException("Annotated element is not loadable as an instance", e, processingEnv, r); } }
Example 17
Source File: ElementUtilitiesEx.java From netbeans with Apache License 2.0 | 4 votes |
/** * Resolves a method by its name, signature and parent class * @param parentClass The parent class * @param methodName The method name * @param signature The VM signature of the method * @return Returns an ExecutableElement representing the method or null */ public static ExecutableElement resolveMethodByName(CompilationInfo ci, TypeElement parentClass, String methodName, String signature) { // TODO: static initializer if ((parentClass == null) || (methodName == null)) { return null; } ExecutableElement foundMethod = null; boolean found = false; List<ExecutableElement> methods; if (methodName.equals(VM_CONSTRUCTUR_SIG)) { methods = ElementFilter.constructorsIn(ci.getElements().getAllMembers(parentClass)); // } else if (methodName.equals(VM_INITIALIZER_SIG)) { // methods = constructorsIn(parentClass.getEnclosedElements()); } else { // retrieve all defined methods methods = ElementFilter.methodsIn(ci.getElements().getAllMembers(parentClass)); } // loop over all methods for (ExecutableElement method : methods) { // match the current method against the required method name and signature if (methodNameMatch(methodName, method)) { if (signature != null && methodSignatureMatch(ci, signature, method)) { foundMethod = method; found = true; break; } foundMethod = method; // keeping the track of the closest match } } if (!found) { ProfilerLogger.debug("Could not find exact signature match, opening at first method with same name: " + foundMethod); // NOI18N } return foundMethod; }
Example 18
Source File: JavaHintsAnnotationProcessor.java From netbeans with Apache License 2.0 | 4 votes |
private boolean verifyHintAnnotationAcceptable(Element hint) { AnnotationMirror hintMirror = findAnnotation(hint.getAnnotationMirrors(), "org.netbeans.spi.java.hints.Hint"); if (hintMirror == null) return false; String id = getAttributeValue(hintMirror, "id", String.class); if (id == null || id.isEmpty()) { switch (hint.getKind()) { case CLASS: case METHOD: break; //OK default: //compiler should have already warned about this return false; } } TypeMirror customizerProviderType = getAttributeValue(hintMirror, "customizerProvider", TypeMirror.class); if (customizerProviderType != null) { Element customizerProvider = processingEnv.getTypeUtils().asElement(customizerProviderType); if (customizerProvider != null) { if (customizerProvider.getKind() != ElementKind.CLASS) { TypeElement customizerProviderInterface = processingEnv.getElementUtils().getTypeElement("org.netbeans.spi.java.hints.CustomizerProvider"); if (customizerProviderInterface != null && !customizerProviderInterface.equals(customizerProvider)) { processingEnv.getMessager().printMessage(Kind.ERROR, "Customizer provider must be a concrete class", hint, hintMirror, getAttributeValueDescription(hintMirror, "customizerProvider")); } } else { TypeElement customizerProviderClazz = (TypeElement) customizerProvider; if (!customizerProviderClazz.getModifiers().contains(Modifier.PUBLIC)) { processingEnv.getMessager().printMessage(Kind.ERROR, "Customizer provider must be public", hint, hintMirror, getAttributeValueDescription(hintMirror, "customizerProvider")); } if ( customizerProviderClazz.getEnclosingElement().getKind() != ElementKind.PACKAGE && !customizerProviderClazz.getModifiers().contains(Modifier.STATIC)) { processingEnv.getMessager().printMessage(Kind.ERROR, "Customizer provider must be non-static innerclass", hint, hintMirror, getAttributeValueDescription(hintMirror, "customizerProvider")); } boolean foundDefaultConstructor = false; for (ExecutableElement ee : ElementFilter.constructorsIn(customizerProviderClazz.getEnclosedElements())) { if (ee.getParameters().isEmpty()) { foundDefaultConstructor = true; if (!ee.getModifiers().contains(Modifier.PUBLIC)) { processingEnv.getMessager().printMessage(Kind.ERROR, "Customizer provider must provide a public default constructor", hint, hintMirror, getAttributeValueDescription(hintMirror, "customizerProvider")); } break; } } if (!foundDefaultConstructor) { processingEnv.getMessager().printMessage(Kind.ERROR, "Customizer provider must provide a public default constructor", hint, hintMirror, getAttributeValueDescription(hintMirror, "customizerProvider")); } } } } return true; }
Example 19
Source File: ExtractSuperclassRefactoringPlugin.java From netbeans with Apache License 2.0 | 4 votes |
private void addConstructors(final TypeElement origClass) { final GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy); // cache of already resolved constructors final Set<Element> added = new HashSet<Element>(); for (ExecutableElement constr : ElementFilter.constructorsIn(origClass.getEnclosedElements())) { if (workingCopy.getElementUtilities().isSynthetic(constr)) { continue; } TreePath path = workingCopy.getTrees().getPath(constr); MethodTree mc = (MethodTree) (path != null? path.getLeaf(): null); if (mc != null) { for (StatementTree stmt : mc.getBody().getStatements()) { // search super(...); statement if (stmt.getKind() == Tree.Kind.EXPRESSION_STATEMENT) { ExpressionStatementTree estmt = (ExpressionStatementTree) stmt; boolean isSyntheticSuper = workingCopy.getTreeUtilities().isSynthetic(workingCopy.getTrees().getPath(path.getCompilationUnit(), estmt)); ExpressionTree expr = estmt.getExpression(); TreePath expath = workingCopy.getTrees().getPath(path.getCompilationUnit(), expr); Element el = workingCopy.getTrees().getElement(expath); if (el != null && el.getKind() == ElementKind.CONSTRUCTOR && added.add(el)) { ExecutableElement superclassConstr = (ExecutableElement) el; MethodInvocationTree invk = (MethodInvocationTree) expr; // create constructor block with super call BlockTree block = isSyntheticSuper ? make.Block(Collections.<StatementTree>emptyList(), false) : make.Block(Collections.<StatementTree>singletonList( make.ExpressionStatement( make.MethodInvocation( Collections.<ExpressionTree>emptyList(), invk.getMethodSelect(), params2Arguments(make, superclassConstr.getParameters()) ))), false); // create constructor MethodTree newConstr = make.Method(superclassConstr, block); newConstr = removeRuntimeExceptions(workingCopy, superclassConstr, make, newConstr); newConstr = genUtils.importFQNs(newConstr); members.add(newConstr); } } // take just first statement super(...) break; } } } }
Example 20
Source File: WebServiceVisitor.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
protected boolean isLegalImplementation(WebService webService, TypeElement classElement) { boolean isStateful = isStateful(classElement); Collection<Modifier> modifiers = classElement.getModifiers(); if (!modifiers.contains(Modifier.PUBLIC)) { builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_NOT_PUBLIC(classElement.getQualifiedName()), classElement); return false; } if (modifiers.contains(Modifier.FINAL) && !isStateful) { builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_IS_FINAL(classElement.getQualifiedName()), classElement); return false; } if (modifiers.contains(Modifier.ABSTRACT) && !isStateful) { builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_IS_ABSTRACT(classElement.getQualifiedName()), classElement); return false; } boolean hasDefaultConstructor = false; for (ExecutableElement constructor : ElementFilter.constructorsIn(classElement.getEnclosedElements())) { if (constructor.getModifiers().contains(Modifier.PUBLIC) && constructor.getParameters().isEmpty()) { hasDefaultConstructor = true; break; } } if (!hasDefaultConstructor && !isStateful) { if (classElement.getEnclosingElement() != null && !modifiers.contains(Modifier.STATIC)) { builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_IS_INNERCLASS_NOT_STATIC( classElement.getQualifiedName()), classElement); return false; } builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_NO_DEFAULT_CONSTRUCTOR( classElement.getQualifiedName()), classElement); return false; } if (webService.endpointInterface().isEmpty()) { if (!methodsAreLegal(classElement)) return false; } else { TypeElement interfaceElement = getEndpointInterfaceElement(webService.endpointInterface(), classElement); if (!classImplementsSei(classElement, interfaceElement)) return false; } return true; }