javax.lang.model.util.ElementFilter Java Examples
The following examples show how to use
javax.lang.model.util.ElementFilter.
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: TypeModeler.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public static TypeElement getDeclaringClassMethod(TypeElement theClass, String methodName, TypeMirror[] args) { TypeElement retClass = null; if (theClass.getKind().equals(ElementKind.CLASS)) { TypeMirror superClass = theClass.getSuperclass(); if (!superClass.getKind().equals(TypeKind.NONE)) retClass = getDeclaringClassMethod(superClass, methodName, args); } if (retClass == null) { for (TypeMirror interfaceType : theClass.getInterfaces()) { retClass = getDeclaringClassMethod(interfaceType, methodName, args); } } if (retClass == null) { Collection<? extends ExecutableElement> methods = ElementFilter.methodsIn(theClass.getEnclosedElements()); for (ExecutableElement method : methods) { if (method.getSimpleName().toString().equals(methodName)) { retClass = theClass; break; } } } return retClass; }
Example #2
Source File: JavahTask.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { Set<TypeElement> classes = getAllClasses(ElementFilter.typesIn(roundEnv.getRootElements())); if (classes.size() > 0) { checkMethodParameters(classes); g.setProcessingEnvironment(processingEnv); g.setClasses(classes); g.run(); } } catch (CompletionFailure cf) { messager.printMessage(ERROR, getMessage("class.not.found", cf.sym.getQualifiedName().toString())); } catch (ClassNotFoundException cnfe) { messager.printMessage(ERROR, getMessage("class.not.found", cnfe.getMessage())); } catch (IOException ioe) { messager.printMessage(ERROR, getMessage("io.exception", ioe.getMessage())); } catch (Util.Exit e) { exit = e; } return true; }
Example #3
Source File: JavaSourceHelper.java From jeddict with Apache License 2.0 | 6 votes |
public static TypeElement getXmlRepresentationClass(TypeElement typeElement, String defaultSuffix) { List<ExecutableElement> methods = ElementFilter.methodsIn(typeElement.getEnclosedElements()); for (ExecutableElement method : methods) { List<? extends AnnotationMirror> anmirs = method.getAnnotationMirrors(); AnnotationMirror mirrorHttpMethod = findAnnotation(anmirs, JAXRSConstants.GET); if (mirrorHttpMethod != null) { TypeMirror tm = method.getReturnType(); if (tm != null && tm.getKind() == TypeKind.DECLARED) { TypeElement returnType = (TypeElement) ((DeclaredType) tm).asElement(); if (returnType.getSimpleName().toString().endsWith(defaultSuffix)) { return returnType; } } } } return null; }
Example #4
Source File: IntroduceLocalExtensionTransformer.java From netbeans with Apache License 2.0 | 6 votes |
@Override public boolean accept(CompilationInfo info, TypeMirror tm) { if (!super.accept(info, tm)) { return false; } TypeElement clazz = info.getElements().getTypeElement(fqn); if (clazz == null) { return false; } for (ExecutableElement m : ElementFilter.methodsIn(clazz.getEnclosedElements())) { if (m.getSimpleName().contentEquals(methodName)) { return true; } } return false; }
Example #5
Source File: GeneratorUtilitiesTest.java From netbeans with Apache License 2.0 | 6 votes |
public void run(WorkingCopy copy) throws Exception { copy.toPhase(JavaSource.Phase.RESOLVED); TreePath tp = copy.getTreeUtilities().pathFor(offset); assertTrue(TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())); ClassTree ct = (ClassTree)tp.getLeaf(); TypeElement te = (TypeElement)copy.getTrees().getElement(tp); assertNotNull(te); List<? extends VariableElement> vars = ElementFilter.fieldsIn(te.getEnclosedElements()); TypeElement sup = (TypeElement)((DeclaredType)te.getSuperclass()).asElement(); assertNotNull(sup); List<? extends ExecutableElement> ctors = sup.getQualifiedName().contentEquals("java.lang.Object") ? null : ElementFilter.constructorsIn(sup.getEnclosedElements()); if (ctors != null) numCtorsValidator.accept(ctors.size()); GeneratorUtilities utilities = GeneratorUtilities.get(copy); assertNotNull(utilities); ClassTree newCt = utilities.insertClassMember(ct, utilities.createConstructor(te, vars, ctors != null ? ctors.get(ctorToUse) : null)); copy.rewrite(ct, newCt); }
Example #6
Source File: JNIWriter.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Including super class fields. */ List<VariableElement> getAllFields(TypeElement subclazz) { List<VariableElement> fields = new ArrayList<VariableElement>(); TypeElement cd = null; Stack<TypeElement> s = new Stack<TypeElement>(); cd = subclazz; while (true) { s.push(cd); TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass())); if (c == null) break; cd = c; } while (!s.empty()) { cd = s.pop(); fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements())); } return fields; }
Example #7
Source File: MoreElements.java From auto-parcel with Apache License 2.0 | 6 votes |
private static void getLocalAndInheritedMethods( PackageElement pkg, TypeElement type, SetMultimap<String, ExecutableElement> methods) { for (TypeMirror superInterface : type.getInterfaces()) { getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(superInterface), methods); } if (type.getSuperclass().getKind() != TypeKind.NONE) { // Visit the superclass after superinterfaces so we will always see the implementation of a // method after any interfaces that declared it. getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(type.getSuperclass()), methods); } for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { if (!method.getModifiers().contains(Modifier.STATIC) && methodVisibleFromPackage(method, pkg)) { methods.put(method.getSimpleName().toString(), method); } } }
Example #8
Source File: ManagedBeansAnalizer.java From netbeans with Apache License 2.0 | 6 votes |
private void checkCtor( TypeElement element, WebBeansModel model, Result result ) { List<ExecutableElement> ctors = ElementFilter.constructorsIn( element.getEnclosedElements()); for (ExecutableElement ctor : ctors) { Set<Modifier> modifiers = ctor.getModifiers(); if ( modifiers.contains( Modifier.PRIVATE )){ continue; } List<? extends VariableElement> parameters = ctor.getParameters(); if ( parameters.size() ==0 ){ return; } if ( AnnotationUtil.hasAnnotation(ctor, AnnotationUtil.INJECT_FQN, model.getCompilationController())) { return; } } // there is no non-private ctors without params or annotated with @Inject result.addNotification( Severity.WARNING, element, model, NbBundle.getMessage(ManagedBeansAnalizer.class, "WARN_QualifierNoCtorClass")); // NOI18N }
Example #9
Source File: AutoParcelProcessor.java From auto-parcel with Apache License 2.0 | 6 votes |
/** * This method returns a list of all non private fields. If any <code>private</code> fields is * found, the method errors out * * @param type element * @return list of all non-<code>private</code> fields */ private List<VariableElement> getParcelableFieldsOrError(TypeElement type) { List<VariableElement> allFields = ElementFilter.fieldsIn(type.getEnclosedElements()); List<VariableElement> nonPrivateFields = new ArrayList<>(); for (VariableElement field : allFields) { if (!field.getModifiers().contains(PRIVATE)) { nonPrivateFields.add(field); } else { // return error, PRIVATE fields are not allowed mErrorReporter.abortWithError("getFieldsError error, PRIVATE fields not allowed", type); } } return nonPrivateFields; }
Example #10
Source File: T6458749.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv) { if (!renv.processingOver()) { for(TypeElement e : ElementFilter.typesIn(renv.getRootElements())) { System.out.printf("Element %s:%n", e.toString()); try { for (TypeParameterElement tp : e.getTypeParameters()) { System.out.printf("Type param %s", tp.toString()); if (! tp.getEnclosedElements().isEmpty()) { throw new AssertionError("TypeParameterElement.getEnclosedElements() should return empty list"); } } } catch (NullPointerException npe) { throw new AssertionError("NPE from TypeParameterElement.getEnclosedElements()", npe); } } } return true; }
Example #11
Source File: Gen.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Including super classes' fields. */ List<VariableElement> getAllFields(TypeElement subclazz) { List<VariableElement> fields = new ArrayList<>(); TypeElement cd = null; Stack<TypeElement> s = new Stack<>(); cd = subclazz; while (true) { s.push(cd); TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass())); if (c == null) break; cd = c; } while (!s.empty()) { cd = s.pop(); fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements())); } return fields; }
Example #12
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 #13
Source File: Gen.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
/** * Including super classes' fields. */ List<VariableElement> getAllFields(TypeElement subclazz) { List<VariableElement> fields = new ArrayList<VariableElement>(); TypeElement cd = null; Stack<TypeElement> s = new Stack<TypeElement>(); cd = subclazz; while (true) { s.push(cd); TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass())); if (c == null) break; cd = c; } while (!s.empty()) { cd = s.pop(); fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements())); } return fields; }
Example #14
Source File: BindingAnnotationProcessor.java From jlibs with Apache License 2.0 | 6 votes |
private void process(Binding binding, TypeElement c){ for(ExecutableElement method: ElementFilter.methodsIn(c.getEnclosedElements())){ for(AnnotationMirror mirror: method.getAnnotationMirrors()){ if(BINDING_ELEMENT.matches(mirror)) BINDING_ELEMENT.consume(binding, method, mirror); else if(BINDING_START.matches(mirror)) BINDING_START.consume(binding, method, mirror); else if(BINDING_TEXT.matches(mirror)) BINDING_TEXT.consume(binding, method, mirror); else if(BINDING_FINISH.matches(mirror)) BINDING_FINISH.consume(binding, method, mirror); else if(RELATION_START.matches(mirror)) RELATION_START.consume(binding, method, mirror); else if(RELATION_FINISH.matches(mirror)) RELATION_FINISH.consume(binding, method, mirror); } } }
Example #15
Source File: TypeSimplifierTest.java From RetroFacebook with Apache License 2.0 | 6 votes |
public void testIsCastingUnchecked() { TypeElement erasureClass = typeElementOf("Erasure"); List<VariableElement> fields = ElementFilter.fieldsIn(erasureClass.getEnclosedElements()); for (VariableElement field : fields) { String fieldName = field.getSimpleName().toString(); boolean expectUnchecked; if (fieldName.endsWith("Yes")) { expectUnchecked = true; } else if (fieldName.endsWith("No")) { expectUnchecked = false; } else { throw new AssertionError("Fields in Erasure class must end with Yes or No: " + fieldName); } TypeMirror fieldType = field.asType(); boolean actualUnchecked = TypeSimplifier.isCastingUnchecked(fieldType); assertEquals("Unchecked-cast status for " + fieldType, expectUnchecked, actualUnchecked); } }
Example #16
Source File: JNIWriter.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** * Including super class fields. */ List<VariableElement> getAllFields(TypeElement subclazz) { List<VariableElement> fields = new ArrayList<VariableElement>(); TypeElement cd = null; Stack<TypeElement> s = new Stack<TypeElement>(); cd = subclazz; while (true) { s.push(cd); TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass())); if (c == null) break; cd = c; } while (!s.empty()) { cd = s.pop(); fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements())); } return fields; }
Example #17
Source File: JavahTask.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { Set<TypeElement> classes = getAllClasses(ElementFilter.typesIn(roundEnv.getRootElements())); if (classes.size() > 0) { checkMethodParameters(classes); g.setProcessingEnvironment(processingEnv); g.setClasses(classes); g.run(); } } catch (CompletionFailure cf) { messager.printMessage(ERROR, getMessage("class.not.found", cf.sym.getQualifiedName().toString())); } catch (ClassNotFoundException cnfe) { messager.printMessage(ERROR, getMessage("class.not.found", cnfe.getMessage())); } catch (IOException ioe) { messager.printMessage(ERROR, getMessage("io.exception", ioe.getMessage())); } catch (Util.Exit e) { exit = e; } return true; }
Example #18
Source File: TypeDefUtilsTest.java From sundrio with Apache License 2.0 | 6 votes |
@Test public void testCombineTwoTerminal() throws Exception { TypeElement typeElement = elements.getTypeElement(TwoTerminal.class.getCanonicalName()); List<ExecutableElement> methods = ElementFilter.methodsIn(typeElement.getEnclosedElements()); ExecutableElement left = methods.get(0); ExecutableElement right = methods.get(1); TypeDef leftClazz = executableToInterface(dslContext, left); TypeDef rightClazz = executableToInterface(dslContext, right); TypeDef combined = Combine.TYPEDEFS.apply(Arrays.asList(leftClazz, rightClazz)); Assert.assertNotNull(combined); Assert.assertThat(combined.getName(), CoreMatchers.equalTo("MethodABInterface")); Assert.assertThat(combined.getPackageName(), CoreMatchers.equalTo(getClass().getPackage().getName())); //Assert.assertThat(combined.getParameters().size(), CoreMatchers.is(1)); Assert.assertThat(combined.getExtendsList().size(), CoreMatchers.is(2)); Assert.assertThat(combined.getExtendsList(), CoreMatchers.hasItem(TypeNamed.typeNamed("public interface MethodAInterface<T>"))); Assert.assertThat(combined.getExtendsList(), CoreMatchers.hasItem(TypeNamed.typeNamed("public interface MethodBInterface<T>"))); assertEquals(combined.getAttributes().get(ORIGINAL_RETURN_TYPE), TRANSPARENT_REF); }
Example #19
Source File: ElementsTable.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Returns the "requires" modules for the target module. * @param mdle the target module element * @param onlyTransitive true gets all the requires transitive, otherwise * gets all the non-transitive requires * * @return a set of modules */ private Set<ModuleElement> getModuleRequires(ModuleElement mdle, boolean onlyTransitive) throws ToolException { Set<ModuleElement> result = new HashSet<>(); for (RequiresDirective rd : ElementFilter.requiresIn(mdle.getDirectives())) { ModuleElement dep = rd.getDependency(); if (result.contains(dep)) continue; if (!isMandated(mdle, rd) && onlyTransitive == rd.isTransitive()) { if (!haveModuleSources(dep)) { messager.printWarning(dep, "main.module_not_found", dep.getSimpleName()); } result.add(dep); } else if (isMandated(mdle, rd) && haveModuleSources(dep)) { result.add(dep); } } return result; }
Example #20
Source File: GeneratorUtilitiesTest.java From netbeans with Apache License 2.0 | 6 votes |
public void validate(CompilationInfo info) { TypeElement test = info.getElements().getTypeElement("test.Test"); boolean foundCloneMethod = false; boolean foundToStringMethod = false; for (ExecutableElement ee : ElementFilter.methodsIn(test.getEnclosedElements())) { if (ee.getSimpleName().contentEquals("clone")) { if (ee.getParameters().isEmpty()) { assertFalse(foundCloneMethod); foundCloneMethod = true; } } else if (ee.getSimpleName().contentEquals("toString")) { if (ee.getParameters().isEmpty()) { assertFalse(foundToStringMethod); foundToStringMethod = true; } } } assertTrue(foundCloneMethod); assertTrue(foundToStringMethod); }
Example #21
Source File: WebServiceVisitor.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
protected boolean classImplementsSei(TypeElement classElement, TypeElement interfaceElement) { for (TypeMirror interfaceType : classElement.getInterfaces()) { if (((DeclaredType) interfaceType).asElement().equals(interfaceElement)) return true; } List<ExecutableElement> classMethods = getClassMethods(classElement); boolean implementsMethod; for (ExecutableElement interfaceMethod : ElementFilter.methodsIn(interfaceElement.getEnclosedElements())) { implementsMethod = false; for (ExecutableElement classMethod : classMethods) { if (sameMethod(interfaceMethod, classMethod)) { implementsMethod = true; classMethods.remove(classMethod); break; } } if (!implementsMethod) { builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_NOT_IMPLEMENTED(interfaceElement.getSimpleName(), classElement.getSimpleName(), interfaceMethod), interfaceMethod); return false; } } return true; }
Example #22
Source File: ScopedBeanAnalyzer.java From netbeans with Apache License 2.0 | 6 votes |
private void checkPublicField( TypeElement scopeElement, Element element, WebBeansModel model, Result result ) { if ( AnnotationUtil.DEPENDENT.contentEquals( scopeElement.getQualifiedName())) { return; } result.requireCdiEnabled(element, model); List<VariableElement> fields = ElementFilter.fieldsIn( element.getEnclosedElements()); for (VariableElement field : fields) { Set<Modifier> modifiers = field.getModifiers(); if ( modifiers.contains(Modifier.PUBLIC ) && (!modifiers.contains(Modifier.STATIC) || !model.isCdi11OrLater())){ result.addError(element, model , NbBundle.getMessage(ScopedBeanAnalyzer.class, "ERR_IcorrectScopeWithPublicField", field.getSimpleName().toString())); return; } } }
Example #23
Source File: ResourceImplTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testSimplyAnnotatedField() throws Exception { TestUtilities.copyStringToFileObject(srcFO, "MyClass.java", "public class MyClass {" + " @javax.annotation.Resource" + " private javax.sql.DataSource myResource;" + "}"); IndexingManager.getDefault().refreshIndexAndWait(srcFO.getURL(), null); ClasspathInfo cpi = ClasspathInfo.create(srcFO); final AnnotationModelHelper annotationModelHelper = AnnotationModelHelper.create(cpi); annotationModelHelper.runJavaSourceTask(new Runnable() { public void run() { TypeElement myClass = annotationModelHelper.getCompilationController().getElements().getTypeElement("MyClass"); List<VariableElement> fields = ElementFilter.fieldsIn(myClass.getEnclosedElements()); VariableElement annotatedField = fields.get(0); ResourceImpl resource = new ResourceImpl(annotatedField, myClass, annotationModelHelper); assertEquals("myResource", resource.getName()); assertEquals("javax.sql.DataSource", resource.getType()); assertEquals(ResourceImpl.DEFAULT_AUTHENTICATION_TYPE, resource.getAuthenticationType()); assertEquals(ResourceImpl.DEFAULT_SHAREABLE, resource.getShareable()); assertEquals(ResourceImpl.DEFAULT_MAPPED_NAME, resource.getMappedName()); assertEquals(ResourceImpl.DEFAULT_DESCRIPTION, resource.getDescription()); } }); }
Example #24
Source File: PatternAnalyser.java From netbeans with Apache License 2.0 | 6 votes |
private void resolveTypes(Parameters p) { List<TypeElement> types = ElementFilter.typesIn(p.element.getEnclosedElements()); for (TypeElement typeElement : types) { if ( typeElement.getKind() == ElementKind.CLASS || typeElement.getKind() == ElementKind.INTERFACE ) { PatternAnalyser pa = new PatternAnalyser( p.ci.getFileObject(), ui ); pa.analyzeAll(p.ci, typeElement); ClassPattern cp = new ClassPattern(pa, typeElement.asType(), BeanUtils.nameAsString(typeElement)); currentClassesPatterns.add(cp); } } }
Example #25
Source File: Processor.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element e : roundEnv.getElementsAnnotatedWith(Gen.class)) { Gen gen = e.getAnnotation(Gen.class); try { JavaFileObject source = processingEnv.getFiler().createSourceFile(gen.fileName()); try (Writer out = source.openWriter()) { out.write(gen.content()); } } catch (IOException ex) { throw new IllegalStateException(ex); } } TypeElement generated = processingEnv.getElementUtils().getTypeElement("Generated"); if (generated != null) { Check check = ElementFilter.methodsIn(generated.getEnclosedElements()).get(0).getAnnotation(Check.class); checkCorrectException(check::classValue, "java.lang.Class<java.lang.String>"); checkCorrectException(check::intConstValue, "boolean"); checkCorrectException(check::enumValue, "java.lang.String"); checkCorrectException(check::incorrectAnnotationValue, "java.lang.Deprecated"); checkCorrectException(check::incorrectArrayValue, "<any>"); checkCorrectException(check::incorrectClassValue, "<any>"); seenGenerated = true; } if (roundEnv.processingOver() && !seenGenerated) { Assert.error("Did not see the generated class!"); } return true; }
Example #26
Source File: KeyTest.java From dagger2-sample with Apache License 2.0 | 5 votes |
@Test public void forProvidesMethod_sets() { TypeElement setElement = elements.getTypeElement(Set.class.getCanonicalName()); TypeMirror stringType = elements.getTypeElement(String.class.getCanonicalName()).asType(); TypeMirror setOfStringsType = types.getDeclaredType(setElement, stringType); TypeElement moduleElement = elements.getTypeElement(SetProvidesMethodsModule.class.getCanonicalName()); for (ExecutableElement providesMethod : ElementFilter.methodsIn(moduleElement.getEnclosedElements())) { assertThat( keyFactory.forProvidesMethod((ExecutableType) providesMethod.asType(), providesMethod)) .isEqualTo(new AutoValue_Key( Optional.<Equivalence.Wrapper<AnnotationMirror>>absent(), MoreTypes.equivalence().wrap(setOfStringsType))); } }
Example #27
Source File: JavaSourceHelper.java From netbeans with Apache License 2.0 | 5 votes |
public static String getIdFieldName(JavaSource source) { final String[] fieldName = new String[1]; try { source.runUserActionTask(new AbstractTask<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); TypeElement classElement = getTopLevelClassElement(controller); List<VariableElement> fields = ElementFilter.fieldsIn(classElement.getEnclosedElements()); for (VariableElement field : fields) { List<? extends AnnotationMirror> annotations = field.getAnnotationMirrors(); for (AnnotationMirror annotation : annotations) { if (annotation.toString().equals("@javax.persistence.Id")) { //NOI18N fieldName[0] = field.getSimpleName().toString(); return; } } } } }, true); } catch (IOException ex) { } return fieldName[0]; }
Example #28
Source File: Processor.java From immutables with Apache License 2.0 | 5 votes |
private void processTemplates(Set<? extends Element> templates) { for (TypeElement templateType : ElementFilter.typesIn(templates)) { try { generateTemplateType(templateType); } catch (Exception ex) { processingEnv.getMessager() .printMessage(Diagnostic.Kind.ERROR, ex.getMessage() + "\n\n" + Throwables.getStackTraceAsString(ex), templateType); } } }
Example #29
Source File: LocationOpener.java From netbeans with Apache License 2.0 | 5 votes |
private int getMethodLine(final FileObject fo, final String methodName) { final int[] line = new int[1]; JavaSource javaSource = JavaSource.forFileObject(fo); if (javaSource != null) { try { javaSource.runUserActionTask((CompilationController compilationController) -> { compilationController.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); Trees trees = compilationController.getTrees(); CompilationUnitTree compilationUnitTree = compilationController.getCompilationUnit(); List<? extends Tree> typeDecls = compilationUnitTree.getTypeDecls(); for (Tree tree : typeDecls) { Element element = trees.getElement(trees.getPath(compilationUnitTree, tree)); if (element != null && element.getKind() == ElementKind.CLASS && element.getSimpleName().contentEquals(fo.getName())) { List<? extends ExecutableElement> methodElements = ElementFilter.methodsIn(element.getEnclosedElements()); for (Element child : methodElements) { if (child.getSimpleName().contentEquals(methodName)) { long pos = trees.getSourcePositions().getStartPosition(compilationUnitTree, trees.getTree(child)); line[0] = (int) compilationUnitTree.getLineMap().getLineNumber(pos); break; } } } } }, true); return line[0]; } catch (IOException ioe) { //TODO: Do nothing? } } return 1; }
Example #30
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; }