Java Code Examples for javax.lang.model.util.Elements#getPackageElement()

The following examples show how to use javax.lang.model.util.Elements#getPackageElement() . 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: ElementOverlay.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Element resolve(ASTService ast, Elements elements, String what, Element original, ModuleElement modle) {
    Element result = original;
    
    if (classes.containsKey(what)) {
        result = createElement(ast, elements, what, null, modle);
    }

    if (result == null) {
        result = modle != null ? elements.getTypeElement(modle, what) : elements.getTypeElement(what);
    }

    if (result == null) {
        result = modle != null ? elements.getPackageElement(modle, what) : elements.getPackageElement(what);
    }

    result = createElement(ast, elements, what, result, modle);

    return result;
}
 
Example 2
Source File: MethodCompletion.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@NonNull
private List<? extends Element> getElementListFor(Elements elements, final String importName) {
    if (elements != null && importName != null) {
        PackageElement packageElement = elements.getPackageElement(importName);

        if (packageElement != null) {
            return packageElement.getEnclosedElements();
        } else {
            TypeElement typeElement = elements.getTypeElement(importName);
            if (typeElement != null) {
                return Collections.singletonList(typeElement);
            }
        }
    }
    return Collections.emptyList();
}
 
Example 3
Source File: AnnotatedMixins.java    From Mixin with MIT License 6 votes vote down vote up
/**
 * Get a TypeHandle representing another type in the current processing
 * environment
 */
@Override
public TypeHandle getTypeHandle(String name) {
    name = name.replace('/', '.');

    Elements elements = this.processingEnv.getElementUtils();
    TypeElement element = elements.getTypeElement(name);
    if (element != null) {
        try {
            return new TypeHandle(element);
        } catch (NullPointerException ex) {
            // probably bad package
        }
    }

    int lastDotPos = name.lastIndexOf('.');
    if (lastDotPos > -1) {
        String pkg = name.substring(0, lastDotPos);
        PackageElement packageElement = elements.getPackageElement(pkg);
        if (packageElement != null) {
            return new TypeHandle(packageElement, name);
        }
    }

    return null;
}
 
Example 4
Source File: ElementOverlay.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Element createElement(ASTService ast, Elements elements, String name, Element original, ModuleElement modle) {
    Element el = elementCache.get(name);

    if (el == null) {
        if (original != null) {
            if (original.getKind().isClass() || original.getKind().isInterface()) {
                elementCache.put(name, el = new TypeElementWrapper(ast, elements, (TypeElement) original));
                return el;
            }
            if (original.getKind() == ElementKind.PACKAGE) {
                elementCache.put(name, el = new PackageElementWrapper(ast, elements, (PackageElement) original));
                return el;
            }

            return original;
        }
        
        int lastDot = name.lastIndexOf('.');
        Name simpleName = elements.getName(name.substring(lastDot + 1));
        Name fqnName = elements.getName(name);

        if (classes.containsKey(name)) {
            Element parent = lastDot > 0 ? resolve(ast, elements, name.substring(0, lastDot), modle) : elements.getPackageElement("");

            elementCache.put(name, el = new FakeTypeElement(ast, elements, simpleName, fqnName, name, parent, classes.get(name), modle));
        } else if (packages.contains(name)) {
            elementCache.put(name, el = new FakePackageElement(ast, elements, fqnName, name, simpleName, modle));
        } else {
            return null;//XXX: handling of this null in callers!
        }
    }

    return el;
}
 
Example 5
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Element getElementByFQN(CompilationUnitTree cut, String fqn) {
    Elements elements = copy.getElements();
    Element element = elements.getTypeElement(fqn);
    if (element == null)
        element = elements.getPackageElement(fqn);
    if (element == null)
        element = Symtab.instance(copy.impl.getJavacTask().getContext()).enterClass(
                Modules.instance(copy.impl.getJavacTask().getContext()).getDefaultModule(),
                (com.sun.tools.javac.util.Name)elements.getName(fqn));
    return element;
}
 
Example 6
Source File: NullAwayNativeModels.java    From NullAway with MIT License 5 votes vote down vote up
static void elementStuff(Element e, Elements elems) {
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  e.getAnnotation(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  elems.getPackageElement(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  elems.getTypeElement(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  elems.getDocComment(null);
}
 
Example 7
Source File: EdgeCases.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (round++ != 0)
        return false;

    Elements elements = processingEnv.getElementUtils();
    PackageElement pe = elements.getPackageElement("");

    if (pe == null) {
        System.out.println("null");
    } else {
        ModuleElement mod = (ModuleElement) pe.getEnclosingElement();
        if (mod == null) {
            System.out.println("noModule");
        } else if (mod.isUnnamed()) {
            System.out.println("unnamedModule");
        } else {
            System.out.println(mod);
        }
    }

    ModuleElement m1x = elements.getModuleElement("m1x");
    ModuleElement m2x = elements.getModuleElement("m2x");

    if (m1x != null && m2x != null) {
        System.out.println("m1x: " + (elements.getPackageElement(m1x, "") != null));
        System.out.println("m2x: " + (elements.getPackageElement(m2x, "") != null));
    }

    return false;
}
 
Example 8
Source File: MoreElements.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Get a package by name, even if it has no members. */
@Nullable
public static PackageElement getPackageElementEvenIfEmpty(
    Elements elements, CharSequence packageName) {
  if (JavaVersion.getMajorVersion() <= 8) {
    // In Java 8 and earlier, {@link
    // javax.lang.model.util.Elements#getPackageElement(CharSequence)} returns
    // packages even if they have no members.
    return elements.getPackageElement(packageName);
  } else {
    try {
      // In Java 9 and later, only the new {@link
      // javax.lang.model.util.Elements#getPackageElement(ModuleElement, CharSequence)},
      // which {@link javax.lang.mode.util.Elements#getAllPackageElements} calls, returns empty
      // packages.
      @SuppressWarnings("unchecked")
      Set<? extends PackageElement> packages =
          (Set<? extends PackageElement>)
              getAllPackageElementsMethod.invoke(elements, packageName);
      if (packages.isEmpty()) {
        return null;
      }
      if (packages.size() > 1) {
        // TODO(jtorkkola): Add proper Java 9+ module support.
        throw new IllegalStateException("Found more than one package matching " + packageName);
      }
      return packages.iterator().next();
    } catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example 9
Source File: MoreElementsTest.java    From auto with Apache License 2.0 5 votes vote down vote up
@Before
public void initializeTestElements() {
  Elements elements = compilation.getElements();
  this.javaLangPackageElement = elements.getPackageElement("java.lang");
  this.objectElement = elements.getTypeElement(Object.class.getCanonicalName());
  this.stringElement = elements.getTypeElement(String.class.getCanonicalName());
}
 
Example 10
Source File: GeneratorUtilitiesTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void run(WorkingCopy copy) throws Exception {
    copy.toPhase(JavaSource.Phase.RESOLVED);
    CompilationUnitTree cut = copy.getCompilationUnit();
    Elements elements = copy.getElements();
    Set<Element> imports = new HashSet<Element>();
    GeneratorUtilities utilities = GeneratorUtilities.get(copy);
    assertNotNull(utilities);
    CompilationUnitTree newCut = cut;
    for (String imp : toImport) {
        if (imp.endsWith(".*"))
            imp = imp.substring(0, imp.length() - 2);
        Element el = elements.getTypeElement(imp);
        if (el == null)
            el = elements.getPackageElement(imp);
        if (el == null) {
            int idx = imp.lastIndexOf('.');
            if (idx >= 0) {
                el = elements.getTypeElement(imp.substring(0, idx));
                if (el != null) {
                    String name = imp.substring(idx + 1);
                    for (Element ee : el.getEnclosedElements()) {
                        if (name.contentEquals(ee.getSimpleName())) {                                
                            el = ee;
                            break;
                        }
                    }
                }
            }
        }
        assertNotNull(el);
        if (incremental) {
            newCut = utilities.addImports(newCut, Collections.singleton(el));
        } else {
            imports.add(el);
        }
    }
    if (!imports.isEmpty()) {
        newCut = utilities.addImports(newCut, imports);
    }
    copy.rewrite(cut, newCut);
}
 
Example 11
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void completeThrowsOrPkg(String fqn, String prefix, int substitutionOffset, JavadocContext jdctx) {
    final Elements elements = jdctx.javac.getElements();
    final Set<Element> excludes = new HashSet<Element>();
    String pkgPrefix;
    
    // add declared Throwables        
    ExecutableElement method = (ExecutableElement) jdctx.commentFor;
    for (TypeMirror type : method.getThrownTypes()) {
        if (type.getKind() != TypeKind.DECLARED) continue;
        TypeElement clazz = (TypeElement) ((DeclaredType) type).asElement();
        String typeName = clazz.getSimpleName().toString();
        if (startsWith(typeName, prefix)) {
            String qualTypeName = clazz.getQualifiedName().toString();
            TypeElement typeElement = elements.getTypeElement(qualTypeName);
            if (typeElement == null) {
                continue;
            }
            items.add(JavaCompletionItem.createTypeItem(
                    jdctx.javac, typeElement, (DeclaredType) typeElement.asType(),
                    substitutionOffset, /*XXX:*/typeName != qualTypeName ? jdctx.getReferencesCount() : null,
                    elements.isDeprecated(typeElement), false, false, false, true, false, null));
            excludes.add(typeElement);
        }
    }

    // add other Throwables        
    if (fqn == null) {
        pkgPrefix = prefix;
        addTypes(EnumSet.<ElementKind>of(CLASS),
                findDeclaredType("java.lang.Throwable", elements), // NOI18N
                excludes, prefix, substitutionOffset, jdctx);
        
    } else {
        pkgPrefix = fqn + '.' + prefix;
        
        PackageElement pkgElm = elements.getPackageElement(fqn);
        if (pkgElm != null) {
            addPackageContent(pkgElm,
                    EnumSet.<ElementKind>of(CLASS),
                    findDeclaredType("java.lang.Throwable", elements), // NOI18N
                    excludes, prefix, substitutionOffset, jdctx);
        }
        
        TypeElement typeElm = elements.getTypeElement(fqn);
        if (typeElm != null) {
            // inner classes
            addInnerClasses(typeElm,
                    EnumSet.<ElementKind>of(CLASS),
                    findDeclaredType("java.lang.Throwable", elements), // NOI18N
                    excludes, prefix, substitutionOffset, jdctx);
        }
    }
    
    
    // add packages
    
    for (String pkgName : jdctx.javac.getClasspathInfo().getClassIndex().getPackageNames(pkgPrefix, true, EnumSet.allOf(ClassIndex.SearchScope.class)))
        if (pkgName.length() > 0)
            items.add(JavaCompletionItem.createPackageItem(pkgName, substitutionOffset, false));
}
 
Example 12
Source File: FileSystemClosedTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
void run() throws Exception {
    ToolBox tb = new ToolBox();
    Path jar = createJar(tb);

    Path src = Paths.get("src");
    tb.writeJavaFiles(src, "class C { p1.C1 c1; }");

    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    PrintWriter out = new PrintWriter(System.err, true);
    StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
    List<String> options = Arrays.asList("-classpath", jar.toString(), "-proc:none");
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(src.resolve("C.java"));
    com.sun.source.util.JavacTask task =
            (com.sun.source.util.JavacTask) comp.getTask(out, fm, null, options, null, files);
    task.parse();

    Elements elems = task.getElements();

    try {
        // Use  p1, p1.C1 as a control to verify normal behavior
        PackageElement p1 = elems.getPackageElement("p1");
        TypeElement p1C1 = elems.getTypeElement("p1.C1");
        System.err.println("p1: " + p1 + ";  p1C1: " + p1C1);
        if (p1C1 == null) {
            throw new Exception("p1.C1 not found");
        }

        // Now repeat for p2, p2.C2, closing the file manager early
        PackageElement p2 = elems.getPackageElement("p2");
        System.err.println("closing file manager");
        fm.close();
        TypeElement p2C2 = elems.getTypeElement("p2.C2");
        System.err.println("p2: " + p2 + ";  p2C2: " + p2C2);
        if (p2C2 != null) {
            throw new Exception("p2.C2 found unexpectedly");
        }
    } catch (ClosedFileSystemException e) {
        throw new Exception("unexpected exception thrown", e);
    }

}