javax.lang.model.util.Elements Java Examples

The following examples show how to use javax.lang.model.util.Elements. 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 Project: logging-log4j2   Author: apache   File: PluginProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private String calculatePackage(Elements elements, Element element, String packageName) {
    Name name = elements.getPackageOf(element).getQualifiedName();
    if (name == null) {
        return null;
    }
    String pkgName = name.toString();
    if (packageName == null) {
        return pkgName;
    }
    if (pkgName.length() == packageName.length()) {
        return packageName;
    }
    if (pkgName.length() < packageName.length() && packageName.startsWith(pkgName)) {
        return pkgName;
    }

    return commonPrefix(pkgName, packageName);
}
 
Example #2
Source Project: netbeans   Author: apache   File: ElementUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isHidden(Element member, List<? extends Element> members, Elements elements, Types types) {
    for (ListIterator<? extends Element> it = members.listIterator(); it.hasNext();) {
        Element hider = it.next();
        if (hider == member)
            return true;
        if (hider.getSimpleName().contentEquals(member.getSimpleName())) {
            if (elements.hides(member, hider)) {
                it.remove();
            } else {
                if (member instanceof VariableElement && hider instanceof VariableElement
                        && (!member.getKind().isField() || hider.getKind().isField()))
                    return true;
                TypeMirror memberType = member.asType();
                TypeMirror hiderType = hider.asType();
                if (memberType.getKind() == TypeKind.EXECUTABLE && hiderType.getKind() == TypeKind.EXECUTABLE) {
                    if (types.isSubsignature((ExecutableType)hiderType, (ExecutableType)memberType))
                        return true;
                } else {
                    return false;
                }
            }
        }
    }
    return false;
}
 
Example #3
Source Project: sundrio   Author: sundrio   File: BuilderContextManager.java    License: Apache License 2.0 6 votes vote down vote up
public static BuilderContext create(Elements elements, Types types, Boolean validationEnabled, Boolean generateBuilderPackage, String packageName, Inline... inlineables) {
    if (context == null) {
        context = new BuilderContext(elements, types, generateBuilderPackage, validationEnabled, packageName, inlineables);
        return context;
    } else {
        if (!packageName.equals(context.getBuilderPackage())) {
            throw new IllegalStateException("Cannot use different builder package names in a single project. Used:"
                    + packageName + " but package:"
                    + context.getGenerateBuilderPackage() + " already exists.");
        } else if (!generateBuilderPackage.equals(context.getGenerateBuilderPackage())) {
            throw new IllegalStateException("Cannot use different values for generate builder package in a single project.");
        } else {
            return context;
        }
    }
}
 
Example #4
Source Project: vertx-codegen   Author: vert-x3   File: ModuleInfo.java    License: Apache License 2.0 6 votes vote down vote up
public static DeclaredType resolveJsonMapper(Elements elementUtils, Types typeUtils, PackageElement pkgElt, DeclaredType javaType) {
  PackageElement result = resolveFirstModuleGenAnnotatedPackageElement(elementUtils, pkgElt);
  if (result != null) {
    TypeElement jsonMapperElt = elementUtils.getTypeElement("io.vertx.core.spi.json.JsonMapper");
    TypeParameterElement typeParamElt = jsonMapperElt.getTypeParameters().get(0);
    return elementUtils
      .getAllAnnotationMirrors(pkgElt)
      .stream()
      .filter(am -> am.getAnnotationType().toString().equals(ModuleGen.class.getName()))
      .flatMap(am -> am.getElementValues().entrySet().stream())
      .filter(e -> e.getKey().getSimpleName().toString().equals("mappers"))
      .flatMap(e -> ((List<AnnotationValue>) e.getValue().getValue()).stream())
      .map(annotationValue -> (DeclaredType) annotationValue.getValue())
      .filter(dt -> {
        TypeMirror mapperType = Helper.resolveTypeParameter(typeUtils, dt, typeParamElt);
        return mapperType != null && mapperType.getKind() == TypeKind.DECLARED && typeUtils.isSameType(mapperType, javaType);
      })
      .findFirst()
      .orElse(null);
  }
  return null;
}
 
Example #5
Source Project: RxPay   Author: simplezhli   File: ClassEntity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param elementUtils
 * @param typeUtils
 * @param element      current anntated class
 */
public ClassEntity(Elements elementUtils, Types typeUtils, TypeElement element) {
    elementWeakCache = new WeakReference<TypeElement>(element);
    this.classPackageName = elementUtils.getPackageOf(element).getQualifiedName().toString();
    this.modifierSet = element.getModifiers();
    this.className = element.toString();
    annotationMirrors = element.getAnnotationMirrors();
    this.classSimpleName = element.getSimpleName();
    this.classQualifiedName = element.getQualifiedName();
    if ("java.lang.Object".equals(element.getSuperclass().toString())){
        this.superclass = null;
    }else{
        this.superclass = element.getSuperclass().toString();
    }
    List<? extends TypeMirror> interfaces = element.getInterfaces();

    for (TypeMirror anInterface : interfaces){
        this.interfaces.add(typeUtils.asElement(anInterface).toString());
    }
}
 
Example #6
Source Project: kripton   Author: xcesco   File: AnnotationUtility.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extract from an annotation of a method the attribute value specified. IF NO ELEMENT WAS FOUND, AN EMPTY LIST WILL RETURN.
 *
 * @param item the item
 * @param annotationClass the annotation class
 * @param attributeName the attribute name
 * @return attribute value extracted as class typeName
 */
public static List<String> extractAsStringArray(Element item, Class<? extends Annotation> annotationClass, AnnotationAttributeType attributeName) {
	final Elements elementUtils=BaseProcessor.elementUtils;
	final One<List<String>> result = new One<List<String>>(new ArrayList<String>());

	extractString(elementUtils, item, annotationClass, attributeName, new OnAttributeFoundListener() {

		@Override
		public void onFound(String value) {
			List<String> list = AnnotationUtility.extractAsArrayOfString(value);

			result.value0 = list;
		}
	});

	return result.value0;
}
 
Example #7
Source Project: buck   Author: facebook   File: DefaultSourceOnlyAbiRuleInfo.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private String getOwningTarget(
    Elements elements, Element element, ImmutableList<JavaAbiInfo> classpath) {
  TypeElement enclosingType = MoreElements.getTypeElement(element);
  String classFilePath =
      elements.getBinaryName(enclosingType).toString().replace('.', File.separatorChar)
          + ".class";

  for (JavaAbiInfo info : classpath) {
    if (info.jarContains(classFilePath)) {
      return info.getBuildTarget().getUnflavoredBuildTarget().toString();
    }
  }

  return null;
}
 
Example #8
Source Project: buck   Author: facebook   File: InterfaceValidator.java    License: Apache License 2.0 6 votes vote down vote up
public ValidatingListener(
    Diagnostic.Kind messageKind,
    Elements elements,
    Types types,
    Trees trees,
    SourceOnlyAbiRuleInfo ruleInfo,
    FileManagerSimulator fileManager,
    CompilerTypeResolutionSimulator compilerResolver,
    CompilationUnitTree compilationUnit) {
  this.messageKind = messageKind;
  this.trees = trees;
  this.ruleInfo = ruleInfo;
  this.fileManager = fileManager;
  this.compilerResolver = compilerResolver;
  completer = new CompletionSimulator(fileManager);
  imports =
      new ImportsTracker(
          elements,
          types,
          (PackageElement)
              Objects.requireNonNull(trees.getElement(new TreePath(compilationUnit))));
  treeBackedResolver = new TreeBackedTypeResolutionSimulator(elements, trees, compilationUnit);
}
 
Example #9
Source Project: bazel   Author: bazelbuild   File: ProcessorUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the contents of a {@code Class}-typed field in an annotation.
 *
 * <p>Taken & adapted from AutoValueProcessor.java
 *
 * <p>This method is needed because directly reading the value of such a field from an
 * AnnotationMirror throws:
 *
 * <pre>
 * javax.lang.model.type.MirroredTypeException: Attempt to access Class object for TypeMirror Foo.
 * </pre>
 *
 * @param annotation The annotation to read from.
 * @param fieldName The name of the field to read, e.g. "exclude".
 * @return a set of fully-qualified names of classes appearing in 'fieldName' on 'annotation' on
 *     'element'.
 */
static TypeElement getClassTypeFromAnnotationField(
    Elements elementUtils, AnnotationMirror annotation, String fieldName)
    throws OptionProcessorException {
  for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
      elementUtils.getElementValuesWithDefaults(annotation).entrySet()) {
    if (entry.getKey().getSimpleName().contentEquals(fieldName)) {
      Object annotationField = entry.getValue().getValue();
      if (!(annotationField instanceof DeclaredType)) {
        throw new IllegalStateException(
            String.format(
                "The fieldName provided should only apply to Class<> type annotation fields, "
                    + "but the field's value (%s) couldn't get cast to a DeclaredType",
                entry));
      }
      String qualifiedName =
          ((TypeElement) ((DeclaredType) annotationField).asElement())
              .getQualifiedName()
              .toString();
      return elementUtils.getTypeElement(qualifiedName);
    }
  }
  // Annotation missing the requested field.
  throw new OptionProcessorException(
      null, "No member %s of the %s annotation found for element.", fieldName, annotation);
}
 
Example #10
Source Project: ioc-apt-sample   Author: hymanAndroid   File: ProxyInfo.java    License: Apache License 2.0 5 votes vote down vote up
public ProxyInfo(Elements elementUtils, TypeElement classElement)
{
    this.typeElement = classElement;
    PackageElement packageElement = elementUtils.getPackageOf(classElement);
    String packageName = packageElement.getQualifiedName().toString();
    //classname
    String className = ClassValidator.getClassName(classElement, packageName);
    this.packageName = packageName;
    this.proxyClassName = className + "$$" + PROXY;
}
 
Example #11
Source Project: qpid-broker-j   Author: apache   File: ConfiguredObjectRegistrationGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv)
{
    if (!_elementProcessingDone)
    {
        final Elements elementUtils = processingEnv.getElementUtils();
        final TypeElement managedObjectElement = elementUtils.getTypeElement(MANAGED_OBJECT_CANONICAL_NAME);
        try
        {
            roundEnv.getElementsAnnotatedWith(managedObjectElement).stream()
                    .map(element -> elementUtils.getPackageOf(element))
                    .flatMap(packageElement -> packageElement.getEnclosedElements().stream())
                    .filter(element -> hasAnnotation(element, managedObjectElement))
                    .forEach(annotatedElement -> processAnnotatedElement(elementUtils,
                                                                         managedObjectElement,
                                                                         annotatedElement));

            for (Map.Entry<String, Set<String>> entry : _managedObjectClasses.entrySet())
            {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
                                                         String.format("Generating CO registration for package '%s'", entry.getKey()));
                generateRegistrationFile(entry.getKey(), entry.getValue());
            }
            _managedObjectClasses.clear();
            _typeMap.clear();
            _categoryMap.clear();

            _elementProcessingDone = true;

        }
        catch (Exception e)
        {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error: " + e.getLocalizedMessage());
        }
    }
    return false;
}
 
Example #12
Source Project: ParcelablePlease   Author: sockeqwe   File: SupportedTypes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the variabel element has generics arguments that matches the expected type
 */
public static TypeMirror hasGenericsTypeArgumentOf(Element element, String typeToCheck,
                                                   Elements elements, Types types) {

  if (element.asType().getKind() != TypeKind.DECLARED
      || !(element.asType() instanceof DeclaredType)) {
    ProcessorMessage.error(element, "The field %s in %s doesn't have generic type arguments!",
        element.getSimpleName(), element.asType().toString());
  }

  DeclaredType declaredType = (DeclaredType) element.asType();
  List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();

  if (typeArguments.isEmpty()) {
    ProcessorMessage.error(element, "The field %s in %s doesn't have generic type arguments!",
        element.getSimpleName(), element.asType().toString());
  }

  if (typeArguments.size() > 1) {
    ProcessorMessage.error(element, "The field %s in %s has more than 1 generic type argument!",
        element.getSimpleName(), element.asType().toString());
  }

  // Ok it has a generic argument, check if this extends Parcelable
  TypeMirror argument = typeArguments.get(0);

  if (typeToCheck != null) {
    if (!isOfType(argument, typeToCheck, elements, types)) {
      ProcessorMessage.error(element,
          "The fields %s  generic type argument is not of type  %s! (in %s )",
          element.getSimpleName(), typeToCheck, element.asType().toString());
    }
  }

  // everything is like expected
  return argument;
}
 
Example #13
Source Project: netbeans   Author: apache   File: TestMethodNameGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Collects names of accessible no-argument methods that are present
 * in the given class and its superclasses. Methods inherited from the
 * class's superclasses are taken into account, too.
 * 
 * @param  clazz  class whose methods' names should be collected
 * @param  reservedMethodNames  collection to which the method names
 *                              should be added
 */
private void collectExistingMethodNames(TypeElement clazz,
                                        Collection<String> reservedMethodNames) {
    final Elements elements = workingCopy.getElements();
    List<? extends Element> allMembers = elements.getAllMembers(clazz);
    List<? extends ExecutableElement> methods = ElementFilter.methodsIn(allMembers);
    if (!methods.isEmpty()) {
        for (ExecutableElement method : methods) {
            if (method.getParameters().isEmpty()) {
                reservedMethodNames.add(method.getSimpleName().toString());
            }
        }
    }
}
 
Example #14
Source Project: litho   Author: facebook   File: ProcessorUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets an annotation parameter from an annotation. Usually you can just get the parameter
 * directly, but if the parameter has type {@link Class} it doesn't work, because javac doesn't
 * load classes in the normal manner.
 *
 * @see <a
 *     href="https://area-51.blog/2009/02/13/getting-class-values-from-annotations-in-an-annotationprocessor">this
 *     article</a> for more details.
 */
public static @Nullable <T> T getAnnotationParameter(
    Elements elements,
    Element element,
    Class<?> annotationType,
    String parameterName,
    Class<? extends T> expectedReturnType) {
  List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();

  AnnotationMirror mirror = null;
  for (AnnotationMirror m : annotationMirrors) {
    if (m.getAnnotationType().toString().equals(annotationType.getCanonicalName())) {
      mirror = m;
      break;
    }
  }

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

  for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
      elements.getElementValuesWithDefaults(mirror).entrySet()) {
    if (parameterName.equals(entry.getKey().getSimpleName().toString())) {
      try {
        return expectedReturnType.cast(entry.getValue().getValue());
      } catch (ClassCastException e) {
        throw new ComponentsProcessingException(
            element,
            mirror,
            String.format(
                "Error processing the annotation '%s'. Are your imports set up correctly? The causing error was: %s",
                annotationType.getCanonicalName(), e));
      }
    }
  }

  return null;
}
 
Example #15
Source Project: netbeans   Author: apache   File: ElementOverlay.java    License: Apache License 2.0 5 votes vote down vote up
private ModuleElement moduleOf(Elements elements, Element el) {
    if (el instanceof TypeElementWrapper)
        return moduleOf(elements, ((TypeElementWrapper) el).delegateTo);
    if (el instanceof FakeTypeElement)
        return ((FakeTypeElement) el).modle;
    if (el instanceof PackageElementWrapper)
        return moduleOf(elements, ((PackageElementWrapper) el).delegateTo);
    if (el instanceof FakePackageElement)
        return ((FakePackageElement) el).modle;
    if (el instanceof Symbol)
        return elements.getModuleOf(el);
    return null;
}
 
Example #16
Source Project: kripton   Author: xcesco   File: AnnotationUtility.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Extract from an annotation of a method the attribute value specified.
 *
 * @param elementUtils the element utils
 * @param item the item
 * @param annotationName the annotation name
 * @param attribute the attribute
 * @param listener the listener
 */
static void extractAttributeValue(Elements elementUtils, Element item, String annotationName, AnnotationAttributeType attribute, OnAttributeFoundListener listener) {
	List<? extends AnnotationMirror> annotationList = elementUtils.getAllAnnotationMirrors(item);
	for (AnnotationMirror annotation : annotationList) {			
		if (annotationName.equals(annotation.getAnnotationType().asElement().toString())) {
			// found annotation
			for (Entry<? extends ExecutableElement, ? extends AnnotationValue> annotationItem : elementUtils.getElementValuesWithDefaults(annotation).entrySet()) {
				if (attribute.isEquals(annotationItem.getKey())) {
					listener.onFound(annotationItem.getValue().toString());
					return;
				}
			}
		}
	}
}
 
Example #17
Source Project: FreeBuilder   Author: inferred   File: ModelUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the upper bound of {@code type}.<ul>
 * <li>T -> T
 * <li>? -> Object
 * <li>? extends T -> T
 * <li>? super T -> Object
 * </ul>
 */
public static TypeMirror upperBound(Elements elements, TypeMirror type) {
  if (type.getKind() == TypeKind.WILDCARD) {
    WildcardType wildcard = (WildcardType) type;
    type = wildcard.getExtendsBound();
    if (type == null) {
      type = elements.getTypeElement(Object.class.getName()).asType();
    }
  }
  return type;
}
 
Example #18
Source Project: netbeans   Author: apache   File: EntRefContainerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void writeDD(FileObject referencingFile, final String referencingClass) throws IOException {
    WebModuleImpl jp = project.getLookup().lookup(WebModuleProviderImpl.class).getModuleImpl();
    
    // test if referencing class is injection target
    final boolean[] isInjectionTarget = {false};
    CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() {
        @Override
            public void run(CompilationController controller) throws IOException {
                Elements elements = controller.getElements();
                TypeElement thisElement = elements.getTypeElement(referencingClass);
                if (thisElement!=null)
                    isInjectionTarget[0] = InjectionTargetQuery.isInjectionTarget(controller, thisElement);
            }
        @Override
            public void cancel() {}
    };
    JavaSource refFile = JavaSource.forFileObject(referencingFile);
    if (refFile!=null) {
        refFile.runUserActionTask(task, true);
    }
    
    boolean shouldWrite = isDescriptorMandatory(jp.getJ2eeProfile()) || !isInjectionTarget[0];
    if (shouldWrite) {
        FileObject fo = jp.getDeploymentDescriptor();
        getWebApp().write(fo);
    }
}
 
Example #19
Source Project: hottub   Author: dsrg-uoft   File: T6358786.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(Arrays.asList(file)));
    Elements elements = task.getElements();
    for (TypeElement clazz : task.enter(task.parse())) {
        String doc = elements.getDocComment(clazz);
        if (doc == null)
            throw new AssertionError(clazz.getSimpleName() + ": no doc comment");
        System.out.format("%s: %s%n", clazz.getSimpleName(), doc);
    }
}
 
Example #20
Source Project: hottub   Author: dsrg-uoft   File: Env.java    License: GNU General Public License v2.0 5 votes vote down vote up
void init(DocTrees trees, Elements elements, Types types) {
    this.trees = trees;
    this.elements = elements;
    this.types = types;
    java_lang_Error = elements.getTypeElement("java.lang.Error").asType();
    java_lang_RuntimeException = elements.getTypeElement("java.lang.RuntimeException").asType();
    java_lang_Throwable = elements.getTypeElement("java.lang.Throwable").asType();
    java_lang_Void = elements.getTypeElement("java.lang.Void").asType();
}
 
Example #21
Source Project: kripton   Author: xcesco   File: AnnotationUtility.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Extract from an annotation of a method the attribute value specified.
 *
 * @param method            method to analyze
 * @param annotationClass            annotation to analyze
 * @param attribute the attribute
 * @return attribute value as list of string
 */
public static List<String> extractAsStringArray(ModelMethod method, ModelAnnotation annotationClass, AnnotationAttributeType attribute) {
	final Elements elementUtils=BaseProcessor.elementUtils;
	final One<List<String>> result = new One<List<String>>();
	extractAttributeValue(elementUtils, method.getElement(), annotationClass.getName(), attribute, new OnAttributeFoundListener() {

		@Override
		public void onFound(String value) {
			result.value0 = AnnotationUtility.extractAsArrayOfString(value);
		}
	});

	return result.value0;
}
 
Example #22
Source Project: netbeans   Author: apache   File: Nodes.java    License: Apache License 2.0 5 votes vote down vote up
@CheckForNull
private static FileObject findBinaryInCp(
        @NonNull final Elements elements,
        @NonNull final TypeElement element,
        @NonNull final ClassPath cp) {
    final FileObject file = cp.findResource(String.format(
            "%s.class", //NOI18N
            elements.getBinaryName(element).toString().replace('.', '/'))); //NOI18N
    return file == null ? null : cp.findOwnerRoot(file);
}
 
Example #23
Source Project: auto   Author: google   File: ExtensionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCantConsumeNonExistentMethod() {
  class ConsumeBogusMethod extends NonFinalExtension {
    @Override
    public Set<ExecutableElement> consumeMethods(Context context) {
      // Find Integer.intValue() and try to consume that.
      Elements elementUtils = context.processingEnvironment().getElementUtils();
      TypeElement javaLangInteger = elementUtils.getTypeElement(Integer.class.getName());
      for (ExecutableElement method :
          ElementFilter.methodsIn(javaLangInteger.getEnclosedElements())) {
        if (method.getSimpleName().contentEquals("intValue")) {
          return ImmutableSet.of(method);
        }
      }
      throw new AssertionError("Could not find Integer.intValue()");
    }
  }
  JavaFileObject impl =
      JavaFileObjects.forSourceLines(
          "foo.bar.Baz",
          "package foo.bar;",
          "import com.google.auto.value.AutoValue;",
          "@AutoValue public abstract class Baz {",
          "  abstract String foo();",
          "}");
  Compilation compilation =
      javac()
          .withProcessors(new AutoValueProcessor(ImmutableList.of(new ConsumeBogusMethod())))
          .compile(impl);
  assertThat(compilation)
      .hadErrorContainingMatch(
          "wants to consume a method that is not one of the abstract methods in this class"
              + ".*intValue\\(\\)")
      .inFile(impl)
      .onLineContaining("@AutoValue public abstract class Baz");
}
 
Example #24
Source Project: ShapeView   Author: xwc520   File: FactoryCodeBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public void generateCode(Messager messager, Elements elementUtils, Filer filer) throws IOException {
    TypeElement superClassName = elementUtils.getTypeElement(mSupperClsName);
    String factoryClassName = superClassName.getSimpleName() + SUFFIX;
    PackageElement pkg = elementUtils.getPackageOf(superClassName);
    String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();

    TypeSpec typeSpec = TypeSpec
        .classBuilder(factoryClassName)
        .addModifiers(Modifier.PUBLIC)
        .addMethod(newCreateMethod(elementUtils, superClassName))
        .build();

    // Write file
    JavaFile.builder(packageName, typeSpec).build().writeTo(filer);
}
 
Example #25
Source Project: netbeans   Author: apache   File: JFXProjectUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns set of names of classes of the classType type.
 * 
 * @param classpathMap map of classpaths of all project files
 * @param classType return only classes of this type
 * @return set of class names
 */
public static Set<String> getAppClassNames(@NonNull Collection<? extends FileObject> roots, final @NonNull String classType) {
    final Set<String> appClassNames = new HashSet<>();
    for (FileObject fo : roots) {
        final ClasspathInfo cpInfo = ClasspathInfo.create(fo);
        final JavaSource js = JavaSource.create(cpInfo);
        if (js != null) {
            try { 
                js.runUserActionTask(new Task<CompilationController>() {
                    @Override
                    public void run(CompilationController controller) throws Exception {
                        final ClassIndex classIndex = cpInfo.getClassIndex();
                        final Elements elems = controller.getElements();
                        TypeElement fxAppElement = elems.getTypeElement(classType);
                        ElementHandle<TypeElement> appHandle = ElementHandle.create(fxAppElement);
                        Set<ElementHandle<TypeElement>> appHandles = classIndex.getElements(appHandle, kinds, scopes);
                        for (ElementHandle<TypeElement> elemHandle : appHandles) {
                            appClassNames.add(elemHandle.getQualifiedName());
                        }
                    }
                }, true);
            } catch (Exception e) {

            }
        }
    }
    return appClassNames;
}
 
Example #26
Source Project: auto   Author: google   File: TypeSimplifier.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handles the tricky case where the class being referred to is in {@code java.lang}, but the
 * package of the referring code contains another class of the same name. For example, if the
 * current package is {@code foo.bar} and there is a {@code foo.bar.Compiler}, then we will refer
 * to {@code java.lang.Compiler} by its full name. The plain name {@code Compiler} would reference
 * {@code foo.bar.Compiler} in this case. We need to write {@code java.lang.Compiler} even if the
 * other {@code Compiler} class is not being considered here, so the {@link #ambiguousNames} logic
 * is not enough. We have to look to see if the class exists.
 */
private static String javaLangSpelling(
    Elements elementUtils, String codePackageName, TypeElement typeElement) {
  // If this is java.lang.Thread.State or the like, we have to look for a clash with Thread.
  TypeElement topLevelType = topLevelType(typeElement);
  TypeElement clash =
      elementUtils.getTypeElement(codePackageName + "." + topLevelType.getSimpleName());
  String fullName = typeElement.getQualifiedName().toString();
  return (clash == null) ? fullName.substring("java.lang.".length()) : fullName;
}
 
Example #27
Source Project: paperparcel   Author: grandstaish   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns true if {@code element} is a {@code TypeAdapter} type. */
static boolean isAdapterType(Element element, Elements elements, Types types) {
  TypeMirror typeAdapterType = types.getDeclaredType(
      elements.getTypeElement(TYPE_ADAPTER_CLASS_NAME),
      types.getWildcardType(null, null));
  return types.isAssignable(element.asType(), typeAdapterType);
}
 
Example #28
Source Project: netbeans   Author: apache   File: ElementOverlay.java    License: Apache License 2.0 5 votes vote down vote up
private Collection<? extends Element> getAllMembers(ASTService ast, Elements elements, Element el) {
    List<Element> result = new ArrayList<Element>();

    result.addAll(el.getEnclosedElements());

    for (Element parent : getAllSuperElements(ast, elements, el)) {
        if (!el.equals(parent)) {
            result.addAll(getAllMembers(ast, elements, parent));
        }
    }

    return result;
}
 
Example #29
Source Project: dagger2-sample   Author: yongjhih   File: MembersInjectorGenerator.java    License: Apache License 2.0 5 votes vote down vote up
MembersInjectorGenerator(
    Filer filer,
    Elements elements,
    Types types,
    DependencyRequestMapper dependencyRequestMapper) {
  super(filer);
  this.elements = checkNotNull(elements);
  this.types = checkNotNull(types);
  this.dependencyRequestMapper = dependencyRequestMapper;
}
 
Example #30
Source Project: PrettyBundle   Author: talenguyen   File: ExtraInjectorClassBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private MethodSpec buildInjectMethod(Elements elementUtils) {
    final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("inject")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(TypeVariableName.get(extraClassesGrouped.getExtraAnnotatedClassName()), "target")
            .addParameter(Androids.bundleClass(), "extras");
    addInjectStatement(methodBuilder, "target", elementUtils);
    return methodBuilder
            .build();
}