Java 类javax.lang.model.element.Element 实例源码

项目:openjdk-jdk10    文件:ModuleTestBase.java   
Set<Element> getAllSelectedElements(DocletEnvironment docenv) {
    Set<Element> result = new TreeSet<Element>((Element e1, Element e2) -> {
        // some grouping by kind preferred
        int rc = e1.getKind().compareTo(e2.getKind());
        if (rc != 0) return rc;
        rc = e1.toString().compareTo(e2.toString());
        if (rc != 0) return rc;
        return Integer.compare(e1.hashCode(), e2.hashCode());
    });
    Set<? extends Element> elements = docenv.getIncludedElements();
    for (ModuleElement me : ElementFilter.modulesIn(elements)) {
        addEnclosedElements(docenv, result, me);
    }
    for (PackageElement pe : ElementFilter.packagesIn(elements)) {
        ModuleElement mdle = docenv.getElementUtils().getModuleOf(pe);
        if (mdle != null)
            addEnclosedElements(docenv, result, mdle);
        addEnclosedElements(docenv, result, pe);
    }
    for (TypeElement te : ElementFilter.typesIn(elements)) {
        addEnclosedElements(docenv, result, te);
    }
    return result;
}
项目:easy-plugins    文件:Util.java   
/**
 * Checks that {@code target} is visible from {@code fromPkg}.
 * If {@code fromPkg} is {@code null}, we take that to mean that {@code target} should be visible everywhere.
 * Throws an {@link EasyPluginException} with a proper error message if the target element does not match
 * the visibility constraint.
 * @param eles Elements
 * @param target The target element to check for visibility
 * @param fromPkg The package to check for visibility from.
 *                Null indicates it needs to be globally visible.
 * @throws EasyPluginException if it's not visible
 */
static void checkElementVisibility(Elements eles, Element target, String fromPkg) {
    // I would have used a switch, but that messed up compilation somehow.
    // I guess it generated another class file?
    // Anyways, this works.
    if (target.getKind().isClass() || target.getKind().isInterface()) {
        checkClassVisibility(eles, (TypeElement) target, fromPkg);
    } else if (target.getKind().isField()
            || target.getKind() == ElementKind.METHOD
            || target.getKind() == ElementKind.CONSTRUCTOR) {
        checkMemberVisibility(eles, target, fromPkg);
    } else if (target.getKind() == ElementKind.ENUM_CONSTANT) {
        checkClassVisibility(eles, (TypeElement) target.getEnclosingElement(), fromPkg);
    } else {
        // This isn't an EasyPluginException because our code shouldn't be dumb
        // enough to check the visibility of any other kind of element.
        throw new IllegalArgumentException("Bad kind for element visibility check: " + target.getKind());
    }
}
项目:incubator-netbeans    文件:NPECheck.java   
@Override
public State visitIdentifier(IdentifierTree node, Void p) {
    super.visitIdentifier(node, p);

    Element e = info.getTrees().getElement(getCurrentPath());

    if (e == null || !isVariableElement(e)) {
        return State.POSSIBLE_NULL;
    }
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
        // enum constants are never null
        return State.NOT_NULL;
    }

    State s = variable2State.get((VariableElement) e);
    if (s != null) {
        return s;
    }

    return getStateFromAnnotations(info, e);
}
项目:incubator-netbeans    文件:DeleteTransformer.java   
private void deleteDeclIfMatch(Tree tree, Element elementToFind) {
    if (JavaPluginUtils.isSyntheticPath(workingCopy, getCurrentPath())) {
        return ;
    }

    Element el = workingCopy.getTrees().getElement(getCurrentPath());
    if (isMatch(el, elementToFind)) {
        Tree parent = getCurrentPath().getParentPath().getLeaf();
        Tree newOne = null;
        if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getKind())) {
            newOne = make.removeClassMember((ClassTree) parent, tree);
        } else if (parent.getKind() == Tree.Kind.COMPILATION_UNIT) {
            newOne = make.removeCompUnitTypeDecl((CompilationUnitTree) parent, tree);
        } else if (tree.getKind() == Tree.Kind.VARIABLE) {
            if (parent.getKind() == Tree.Kind.METHOD) {
                newOne = make.removeMethodParameter((MethodTree)parent, (VariableTree) tree);
            } else {
                newOne = make.removeBlockStatement((BlockTree)parent, (VariableTree) tree);
            }
        }
        if (newOne!=null) {
            rewrite(parent,newOne);
        }
    }
}
项目:incubator-netbeans    文件:FindLocalUsagesQuery.java   
@Override
public Void visitClass(ClassTree tree, Void d) {
    Element el = info.getTrees().getElement(getCurrentPath());
    if (toFind.equals(el)) {
        try {
            int[] span = treeUtils.findNameSpan(tree);
            if(span != null) {
                MutablePositionRegion region = createRegion(doc, span[0], span[1]);
                usages.add(region);
            }
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    handleJavadoc(getCurrentPath());
    return super.visitClass(tree, d);
}
项目:prefpin    文件:PrefPinProcessor.java   
private void buildOnChangeBinding(MethodSpec.Builder constructorBuilder, Element element) {
  OnPrefChange onPrefChange = element.getAnnotation(OnPrefChange.class);
  if (onPrefChange != null) {
    int[] resourceIds = onPrefChange.value();

    for (int resourceId : resourceIds) {
      constructorBuilder.addStatement("target.findPreference(target.getString($L))"
          + ".setOnPreferenceChangeListener(new $T(){\n"
          + "@Override public boolean onPreferenceChange($T preference, Object newValue) {\n"
          + "\t\ttarget.$L(preference, newValue);\n"
          + "\t\treturn true;\n"
          + "\t}\n"
          + "})", resourceId, CHANGE_LISTENER, PREFERENCE, element.getSimpleName());
    }
  }
}
项目:incubator-netbeans    文件:CreateElementUtilities.java   
private static List<? extends TypeMirror> computeReturn(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ReturnTree rt = (ReturnTree) parent.getLeaf();

    if (rt.getExpression() == error) {
        TreePath method = findMethod(parent);

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

        Element el = info.getTrees().getElement(method);

        if (el == null || el.getKind() != ElementKind.METHOD) {
            return null;
        }

        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);

        return Collections.singletonList(((ExecutableElement) el).getReturnType());
    }

    return null;
}
项目:javaide    文件:PrintingProcessor.java   
private void printDocComment(Element e) {
    String docComment = elementUtils.getDocComment(e);

    if (docComment != null) {
        // Break comment into lines
        StringTokenizer st = new StringTokenizer(docComment,
                                                          "\n\r");
        indent();
        writer.println("/**");

        while(st.hasMoreTokens()) {
            indent();
            writer.print(" *");
            writer.println(st.nextToken());
        }

        indent();
        writer.println(" */");
    }
}
项目:Pogamut3    文件:ClassCrawler.java   
private List<ParamInfo> getMethodParams(Element classElement) {
    List<ParamInfo> methodParams = new LinkedList<ParamInfo>();
    ExecutableElement methodElement = (ExecutableElement) classElement;

    for (VariableElement methodParam : methodElement.getParameters()) {
        try {
            String name = getParamName(methodParam);
            ParamInfo.Type type = getParamType(methodParam);
            String clsName = getParamClsName(methodParam);

            methodParams.add(new ParamInfo(name, type, clsName));
        } catch (IllegalArgumentException ex) {
            // Do nothing, thrown when we are missing some info.
        }
    }
    return methodParams;
}
项目:incubator-netbeans    文件:GoToSupport.java   
private static int overridableKind(Element el) {
    if (   el.getModifiers().contains(Modifier.FINAL)
        || el.getModifiers().contains(Modifier.PRIVATE)) {
        return -1;
    }

    if (el.getKind().isClass() || el.getKind().isInterface()) {
        return el.getModifiers().contains(Modifier.ABSTRACT) ? 0 : 1;
    }

    if (   el.getKind() == ElementKind.METHOD
        && !el.getModifiers().contains(Modifier.STATIC)
        && !el.getEnclosingElement().getModifiers().contains(Modifier.FINAL)) {
        return el.getModifiers().contains(Modifier.ABSTRACT) ? 2 : 3;
    }

    return -1;
}
项目:javaide    文件:JavacTaskImpl.java   
private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
    for (Env<AttrContext> env: queue) {
        switch (env.tree.getTag()) {
            case JCTree.CLASSDEF:
                JCClassDecl cdef = (JCClassDecl) env.tree;
                if (cdef.sym != null)
                    elems.append(cdef.sym);
                break;
            case JCTree.TOPLEVEL:
                JCCompilationUnit unit = (JCCompilationUnit) env.tree;
                if (unit.packge != null)
                    elems.append(unit.packge);
                break;
        }
    }
    genList.addAll(queue);
}
项目:incubator-netbeans    文件:JavaRefactoringPlugin.java   
/**
 * Checks if the element is still available. Tests if it is still valid.
 * (Was not deleted by matching mechanism.)
 * If element is available, returns null, otherwise it creates problem.
 * (Helper method for refactoring implementation as this problem is
 * general for all refactorings.)
 *
 * @param   e  element to check
 * @param info 
 * @return  problem message or null if the element is valid
 */
protected static Problem isElementAvail(TreePathHandle e, CompilationInfo info) {
    if (e==null) {
        //element is null or is not valid.
        return new Problem(true, NbBundle.getMessage(FindVisitor.class, "DSC_ElNotAvail")); // NOI18N
    } else {
        Element el = e.resolveElement(info);
        String elName = el != null ? el.getSimpleName().toString() : null;
        if (el == null || el.asType().getKind() == TypeKind.ERROR || "<error>".equals(elName)) { // NOI18N
            return new Problem(true, NbBundle.getMessage(FindVisitor.class, "DSC_ElementNotResolved"));
        }

        if ("this".equals(elName) || "super".equals(elName)) { // NOI18N
            return new Problem(true, NbBundle.getMessage(FindVisitor.class, "ERR_CannotRefactorThis", el.getSimpleName()));
        }

        // element is still available
        return null;
    }
}
项目:incubator-netbeans    文件:ElementNode.java   
public ElementNode getNodeForElement(ElementHandle<Element> eh) {

        if (getDescritption().elementHandle != null
                && eh.signatureEquals(getDescritption().elementHandle)) {
            return this;
        }

        Children ch = getChildren();
        if (ch instanceof ElementChilren) {
            for (Node sub : ch.getNodes()) {
                ElementNode result = ((ElementNode) sub).getNodeForElement(eh);
                if (result != null) {
                    return result;
                }
            }
        }

        return null;
    }
项目:incubator-netbeans    文件:GoToSupportTest.java   
public void testGoToTypeVariable() throws Exception {
    final boolean[] wasCalled = new boolean[1];

    performTest("package test; public class Test<TTT> {public void test() {TTT t;}}", 60, new OrigUiUtilsCaller() {
        public void open(FileObject fo, int pos) {
            assertTrue(source == fo);
            assertEquals(32, pos);
            wasCalled[0] = true;
        }
        public void beep() {
            fail("Should not be called.");
        }
        public void open(ClasspathInfo info, Element el) {
            fail("Should not be called.");
        }
    }, false);

    assertTrue(wasCalled[0]);
}
项目:openjdk-jdk10    文件:JavacTaskImpl.java   
private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
    for (Env<AttrContext> env: queue) {
        switch (env.tree.getTag()) {
            case CLASSDEF:
                JCClassDecl cdef = (JCClassDecl) env.tree;
                if (cdef.sym != null)
                    elems.append(cdef.sym);
                break;
            case MODULEDEF:
                JCModuleDecl mod = (JCModuleDecl) env.tree;
                if (mod.sym != null)
                    elems.append(mod.sym);
                break;
            case PACKAGEDEF:
                JCCompilationUnit unit = env.toplevel;
                if (unit.packge != null)
                    elems.append(unit.packge);
                break;
        }
    }
    genList.addAll(queue);
}
项目:incubator-netbeans    文件:ManyToOneImpl.java   
public ManyToOneImpl(final AnnotationModelHelper helper, final Element element, AnnotationMirror manyToOneAnnotation, String name, Map<String, ? extends AnnotationMirror> annByType) {
    this.name = name;
    AnnotationParser parser = AnnotationParser.create(helper);
    parser.expectClass("targetEntity", new DefaultProvider() { // NOI18N
        public Object getDefaultValue() {
            return EntityMappingsUtilities.getElementTypeName(element);
        }
    });
    parser.expectEnumConstantArray("cascade", helper.resolveType("javax.persistence.CascadeType"), new ArrayValueHandler() { // NOI18N
        public Object handleArray(List<AnnotationValue> arrayMembers) {
            return new CascadeTypeImpl(arrayMembers);
        }
    }, parser.defaultValue(new CascadeTypeImpl()));
    parser.expectEnumConstant("fetch", helper.resolveType("javax.persistence.FetchType"), parser.defaultValue("EAGER")); // NOI18N
    parser.expectPrimitive("optional", Boolean.class, parser.defaultValue(true)); // NOI18N
    parseResult = parser.parse(manyToOneAnnotation);

    joinTable = new JoinTableImpl(helper, annByType.get("javax.persistence.JoinTable")); // NOI18N
    joinColumnList = EntityMappingsUtilities.getJoinColumns(helper, annByType);
}
项目:incap    文件:OneToOneAP.java   
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  for (TypeElement annotation : annotations) {
    System.out.println("Processing annotation:" + annotation);
  }

  if (isProcessingDone) {
    return false;
  }

  // generates a class with a constant that contains the name of all classes containing an annotation.
  Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(Annotation1.class);
  Map<String, Set<? extends Element>> mapGeneratedFileNameToOriginatingElements = processElements(annotatedElements);
  generateFiles(filer, mapGeneratedFileNameToOriginatingElements);
  isProcessingDone = true;
  return false;
}
项目:openjdk-jdk10    文件:AnnotationTypeRequiredMemberBuilder.java   
/**
 * Build the member documentation.
 *
 * @param memberDetailsTree the content tree to which the documentation will be added
 * @throws DocletException if an error occurs
 */
protected void buildAnnotationTypeMember(Content memberDetailsTree)
        throws DocletException {
    if (writer == null) {
        return;
    }
    if (hasMembersToDocument()) {
        writer.addAnnotationDetailsMarker(memberDetailsTree);
        Element lastMember = members.get((members.size() - 1));
        for (Element member : members) {
            currentMember = member;
            Content detailsTree = writer.getMemberTreeHeader();
            writer.addAnnotationDetailsTreeHeader(typeElement, detailsTree);
            Content annotationDocTree = writer.getAnnotationDocTreeHeader(
                    currentMember, detailsTree);

            buildAnnotationTypeMemberChildren(annotationDocTree);

            detailsTree.addContent(writer.getAnnotationDoc(
                    annotationDocTree, currentMember == lastMember));
            memberDetailsTree.addContent(writer.getAnnotationDetails(detailsTree));
        }
    }
}
项目:incubator-netbeans    文件:StaticImport.java   
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    WorkingCopy copy = ctx.getWorkingCopy();
    TreePath treePath = ctx.getPath();
    TreePath mitp = treePath.getParentPath();
    if (mitp == null) {
        return;
    }
    Element e = copy.getTrees().getElement(treePath);
    if (e == null || !e.getModifiers().contains(Modifier.STATIC)) {
        return;
    }
    TreeMaker make = copy.getTreeMaker();
    copy.rewrite(treePath.getLeaf(), make.Identifier(sn));
    if (fqn == null) {
        return;
    }
    CompilationUnitTree cut = (CompilationUnitTree) copy.resolveRewriteTarget(copy.getCompilationUnit());
    CompilationUnitTree nue = GeneratorUtilities.get(copy).addImports(cut, Collections.singleton(e));
    copy.rewrite(cut, nue);
}
项目:GitHub    文件:Generics.java   
Generics(Protoclass protoclass, Element element) {
  this.parameters = computeParameters(protoclass, element);
  this.vars = computeVars(parameters);
  if (this.parameters != NO_PARAMETERS) {
    this.declaration = formatParameters(parameters, true, false);
    this.arguments = formatParameters(parameters, false, false);
    this.unknown = formatParameters(parameters, false, true);
  } else {
    this.declaration = "";
    this.arguments = "";
    this.unknown = "";
  }
}
项目:EgTest    文件:SelfTestMessageHandler.java   
private boolean addIfExpected(ExpectedBehavior expected, Element el, String message, Map<String, String> map) {
    EgSelfTest selfTest = el.getAnnotation(EgSelfTest.class);
    if (selfTest != null  &&  expected.equals(selfTest.value())) {
        map.put(JavaModelUtil.key(el), message);
        return true;
    }
    return false;
}
项目:GitHub    文件:Encodings.java   
private Naming inferNaming(Element element, EnumSet<Tag> tags, AtomicReference<StandardNaming> standardNaming) {
  Optional<NamingMirror> namingAnnotation = NamingMirror.find(element);
  if (namingAnnotation.isPresent()) {
    try {
      NamingMirror mirror = namingAnnotation.get();
      Naming naming = Naming.from(mirror.value());
      if (mirror.depluralize()) {
        tags.add(Tag.DEPLURALIZE);
      }
      standardNaming.set(mirror.standard());
      return naming;
    } catch (IllegalArgumentException ex) {
      reporter.withElement(element)
          .annotationNamed(NamingMirror.simpleName())
          .error(ex.getMessage());
    }
  }
  if (element.getKind() == ElementKind.FIELD
      || (element.getKind() == ElementKind.METHOD
      && (element.getModifiers().contains(Modifier.PRIVATE) || tags.contains(Tag.PRIVATE)))) {
    return helperNaming(element.getSimpleName());
  }
  if (tags.contains(Tag.INIT) || tags.contains(Tag.COPY)) {
    return Naming.identity();
  }
  String encodedMethodName = element.getSimpleName().toString();
  return Naming.from("*" + Naming.Usage.CAPITALIZED.apply(encodedMethodName));
}
项目:openjdk-jdk10    文件:Utils.java   
/**
 * Returns a Comparator for packages, by comparing the fully qualified names.
 *
 * @return a Comparator
 */
public Comparator<Element> makePackageComparator() {
    if (packageComparator == null) {
        packageComparator = new Utils.ElementComparator() {
            @Override
            public int compare(Element pkg1, Element pkg2) {
                return compareFullyQualifiedNames(pkg1, pkg2);
            }
        };
    }
    return packageComparator;
}
项目:incubator-netbeans    文件:Utilities.java   
private @NonNull String getVariable(@NonNull Element el) {
    String var = element2Variable.get(el);

    if (var == null) {
        element2Variable.put(el, var = "$" + currentVariableIndex++);
    }

    return var;
}
项目:data-mediator    文件:MediatorAnnotationProcessor.java   
private CodeGenerator getProxyClass(Element element) {
    //element which is annotated .
    TypeElement classElement = (TypeElement) element;
    String qualifiedName = classElement.getQualifiedName().toString();
    CodeGenerator proxyClass = mProxyClassMap.get(qualifiedName);
    if (proxyClass == null) {
        proxyClass = new CodeGenerator(mTypeUtils, mElementUtils, classElement);
        mProxyClassMap.put(qualifiedName, proxyClass);
    }
    return proxyClass;
}
项目:incubator-netbeans    文件:LayerGenerationException.java   
private static AnnotationMirror findAnnotationMirror(Element element, ProcessingEnvironment processingEnv, Class<? extends Annotation> annotation) {
    for (AnnotationMirror ann : element.getAnnotationMirrors()) {
        if (processingEnv.getElementUtils().getBinaryName((TypeElement) ann.getAnnotationType().asElement()).
                contentEquals(annotation.getName())) {
            return ann;
        }
    }
    return null;
}
项目:syndesis    文件:SyndesisExtensionActionProcessor.java   
protected void persistToFile(Element element, Properties props) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    File file = obtainResourceFile(element);
    if (file != null) {
        try (Writer writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
            props.store(writer, "Generated by Syndesis Annotation Processor");
        }
    }
}
项目:incubator-netbeans    文件:Utilities.java   
public static AnnotationMirror findAnnotation(Element element, String annotationClass){
    for (AnnotationMirror ann : element.getAnnotationMirrors()){
        if (annotationClass.equals(ann.getAnnotationType().toString())){
            return ann;
        }
    }

    return null;
}
项目:incubator-netbeans    文件:ImportClass.java   
private FixBase(FileObject file, String fqn, ElementHandle<Element> toImport, String sortText, boolean isValid) {
    this.isValid = isValid;
    this.file = file;
    this.fqn = fqn;
    this.toImport = toImport;
    this.sortText = sortText;
}
项目:sql-first-mapper    文件:SqlFirstAnnotationProcessor.java   
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return false;
    }

    Element globalConfigElement = null;
    try {
        globalConfigElement = prepareGlobalConfig(roundEnv);
        SqlFirstApcConfig globalConfig = globalConfigElement.getAnnotation(SqlFirstApcConfig.class);
        List<DaoDesc> daoDescList = processSqlSource(roundEnv, globalConfig);

        if (globalConfig != null) {
            prepareDaoClassImplementMap(daoDescList, roundEnv);
            DaoWriter daoWriter = new DaoWriter(processingEnv);
            daoWriter.write(daoDescList, globalConfig);
        }
        return !daoDescList.isEmpty();

    } catch (RuntimeException ex) {
        if (globalConfigElement == null) {
            roundEnv.getElementsAnnotatedWith(SqlSource.class).forEach(x ->
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getFullStackTrace(ex), x)
            );
        } else {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getFullStackTrace(ex), globalConfigElement);

        }
    }
    return false;
}
项目:openjdk-jdk10    文件:Utils.java   
private List<Element> getItems0(Element te, boolean filter, Set<ElementKind> kinds) {
    List<Element> elements = new ArrayList<>();
    for (Element e : te.getEnclosedElements()) {
        if (kinds.contains(e.getKind())) {
            if (!filter || shouldDocument(e)) {
                elements.add(e);
            }
        }
    }
    return elements;
}
项目:openjdk-jdk10    文件:Extern.java   
/**
 * Determine if a element item is externally documented.
 *
 * @param element an Element.
 * @return true if the element is externally documented
 */
public boolean isExternal(Element element) {
    if (packageToItemMap == null) {
        return false;
    }
    PackageElement pe = configuration.utils.containingPackage(element);
    if (pe.isUnnamed()) {
        return false;
    }
    return packageToItemMap.get(configuration.utils.getPackageName(pe)) != null;
}
项目:GitHub    文件:ButterKnifeProcessor.java   
private void parseResourceBool(Element element,
    Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> erasedTargetNames) {
  boolean hasError = false;
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Verify that the target type is bool.
  if (element.asType().getKind() != TypeKind.BOOLEAN) {
    error(element, "@%s field type must be 'boolean'. (%s.%s)",
        BindBool.class.getSimpleName(), enclosingElement.getQualifiedName(),
        element.getSimpleName());
    hasError = true;
  }

  // Verify common generated code restrictions.
  hasError |= isInaccessibleViaGeneratedCode(BindBool.class, "fields", element);
  hasError |= isBindingInWrongPackage(BindBool.class, element);

  if (hasError) {
    return;
  }

  // Assemble information on the field.
  String name = element.getSimpleName().toString();
  int id = element.getAnnotation(BindBool.class).value();
  QualifiedId qualifiedId = elementToQualifiedId(element, id);
  BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
  builder.addResource(
      new FieldResourceBinding(getId(qualifiedId), name, FieldResourceBinding.Type.BOOL));

  erasedTargetNames.add(enclosingElement);
}
项目:butterknife-parent    文件:ButterKnifeProcessor.java   
private static boolean hasAnnotationWithName(Element element, String simpleName) {
  for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
    String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString();
    if (simpleName.equals(annotationName)) {
      return true;
    }
  }
  return false;
}
项目:incubator-netbeans    文件:HibernateFindUsagesPlugin.java   
private void findJavaClassUsage(final TreePathHandle treePathHandle,
        RefactoringElementsBag refactoringElements, FileObject classFile) throws IOException {

    // Figure out the class binary name
    final String[] binaryClassName = new String[]{null};
    JavaSource javaSource = JavaSource.forFileObject(classFile);
    if (javaSource == null) {
        return;
    }

    javaSource.runUserActionTask(new Task<CompilationController>() {

        public void run(CompilationController cc) throws IOException {
            cc.toPhase(Phase.ELEMENTS_RESOLVED);
            Element element = treePathHandle.resolveElement(cc);
            if (element == null || element.getKind() != ElementKind.CLASS) {
                return;
            }
            binaryClassName[0] = ElementUtilities.getBinaryName((TypeElement) element);
        }
    }, true);

    String className = binaryClassName[0];
    if (className != null) {
        Map<FileObject, List<OccurrenceItem>> occurrences =
                HibernateRefactoringUtil.getJavaClassOccurrences(mappingFileObjs, className);

        for (FileObject mFileObj : occurrences.keySet()) {
            List<OccurrenceItem> foundPlaces = occurrences.get(mFileObj);
            for( OccurrenceItem foundPlace : foundPlaces ) {
                HibernateRefactoringElement elem = new HibernateRefactoringElement(mFileObj,
                        className,
                        foundPlace.getMatching(),
                        foundPlace.getLocation(),
                        foundPlace.getText());
                refactoringElements.add(query, elem);
            }
        }
    }
}
项目:GeneratorX    文件:GeneratorProcessor.java   
private AnnotatedClass buildAnnotatedClass(TypeElement typeElement) throws
        NoPackageNameException, IOException {

    HashMap<String, TypeMirror> variableMap = new HashMap<>();
    ArrayList<String> variableNames = new ArrayList<>();
    for (Element element : typeElement.getEnclosedElements()) {
        //过滤 字段 的Element
        if (!(element instanceof VariableElement)) {
            continue;
        }
        //过滤 static final 字段
        if (element.getModifiers().contains(STATIC) || element.getModifiers().contains(FINAL)) {
            continue;
        }
        VariableElement variableElement = (VariableElement) element;
        variableNames.add(variableElement.getSimpleName().toString());
        variableMap.put(
                variableElement.getSimpleName().toString(),
                variableElement.asType()
        );
    }

    //打印 用于测试 是否为 parcelable
    if (isParcelable(typeElement)) {
        String message = String.format("Classes %s is parceleble.", ANNOTATION);
        //messager.printMessage(Diagnostic.Kind.OTHER, message, typeElement);
    }
    return new AnnotatedClass(typeElement, variableNames, variableMap,
            isParcelable(typeElement));
}
项目:GitHub    文件:SwitcherModel.java   
private ImmutableList<SwitchOption> constructOptions() {
  ImmutableList.Builder<SwitchOption> builder = ImmutableList.builder();

  for (Element v : containedTypeElement.getEnclosedElements()) {
    if (v.getKind() == ElementKind.ENUM_CONSTANT) {
      String name = v.getSimpleName().toString();
      builder.add(new SwitchOption(name, defaultName.equals(name)));
    }
  }

  return builder.build();
}
项目:react4j    文件:ProcessorUtil.java   
@SuppressWarnings( "SameParameterValue" )
@Nonnull
static AnnotationValue getAnnotationValue( @Nonnull final Elements elements,
                                           @Nonnull final Element typeElement,
                                           @Nonnull final String annotationClassName,
                                           @Nonnull final String parameterName )
{
  final AnnotationValue value = findAnnotationValue( elements, typeElement, annotationClassName, parameterName );
  assert null != value;
  return value;
}
项目:RxAndroidOrm    文件:ModelEntityProxyGenerator.java   
public TypeSpec generate() {
    String idFieldName = Constants.FIELD_ID;
    Element idField = ProcessUtils.getIdField(element);
    if (idField != null)
        idFieldName = ProcessUtils.getObjectName(idField);

    TypeSpec.Builder builder = TypeSpec.classBuilder(ProcessUtils.getObjectName(element) + Constants.MODEL_ENTITY_PROXY)
            .addModifiers(Modifier.PUBLIC)
            .superclass(TypeName.get(element.asType()))
            .addSuperinterface(ClassName.get(Constants.DAO_PACKAGE, Constants.MODEL_ENTITY_PROXY_INTERFACE));

    if (idField == null) {
        builder.addField(TypeName.LONG, Constants.FIELD_ID);
    }

    builder.addMethod(MethodSpec.methodBuilder(Constants.MODEL_ENTITY_PROXY_GET_ID_METHOD)
            .addModifiers(Modifier.PUBLIC)
            .returns(TypeName.LONG)
            .addStatement("return $L", idFieldName)
            .build())
            .addMethod(MethodSpec.methodBuilder(Constants.MODEL_ENTITY_PROXY_SET_ID_METHOD)
                    .addModifiers(Modifier.PUBLIC)
                    .returns(TypeName.VOID)
                    .addParameter(TypeName.LONG, "id")
                    .addStatement("this.$L = id", idFieldName)
                    .build());

    return builder.build();
}
项目:openjdk-jdk10    文件:Messager.java   
private String getDiagSource(Element e) {
    if (e == null) {
        return programName;
    }
    JavacTrees trees = JavacTrees.instance(context);
    TreePath path = trees.getPath(e);
    DocSourcePositions sourcePositions = trees.getSourcePositions();
    JCTree tree = trees.getTree(e);
    CompilationUnitTree cu = path.getCompilationUnit();
    long spos = sourcePositions.getStartPosition(cu, tree);
    long lineNumber = cu.getLineMap().getLineNumber(spos);
    String fname = cu.getSourceFile().getName();
    String posString = fname + ":" + lineNumber;
    return posString;
}