Java Code Examples for javax.lang.model.element.Name

The following examples show how to use javax.lang.model.element.Name. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: netbeans   Source File: EntityClassInfo.java    License: Apache License 2.0 6 votes vote down vote up
private boolean hasAnnotation ( Element element, 
        CompilationController controller, String... annotations )
{
    List<? extends AnnotationMirror> allAnnotationMirrors = 
        controller.getElements().getAllAnnotationMirrors(element);
    for (AnnotationMirror annotationMirror : allAnnotationMirrors) {
        Element annotationElement = annotationMirror.
            getAnnotationType().asElement();
        if ( annotationElement instanceof TypeElement ){
            Name name = ((TypeElement)annotationElement).getQualifiedName();
            for (String  annotation : annotations) {
                if ( name.contentEquals( annotation)){
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 2
Source Project: fit   Source File: FitProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isGetter(Element method) {
  Name methodName = method.getSimpleName();
  if ((!methodName.toString().startsWith("get")) && !methodName.toString().startsWith("is")) {
    return false;
  }
  ExecutableType type = (ExecutableType) method.asType();
  //返回值为void
  if (TypeKind.VOID.equals(type.getReturnType().getKind())) {
    return false;
  }
  //有参数
  if (type.getParameterTypes().size() > 0) {
    return false;
  }

  if (methodName.length() < 4) {
    return false;
  }
  return true;
}
 
Example 3
Source Project: immutables   Source File: AnnotationMirrors.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Void visitAnnotation(AnnotationMirror a, Void p) {
  builder.append('@').append(a.getAnnotationType());

  Map<? extends ExecutableElement, ? extends AnnotationValue> values = a.getElementValues();
  if (!values.isEmpty()) {
    builder.append('(');
    boolean notFirst = false;
    for (Entry<? extends ExecutableElement, ? extends AnnotationValue> e : values.entrySet()) {
      if (notFirst) {
        builder.append(", ");
      }
      notFirst = true;
      Name name = e.getKey().getSimpleName();
      boolean onlyValue = values.size() == 1 && name.contentEquals(ATTRIBUTE_VALUE);
      if (!onlyValue) {
        builder.append(name).append(" = ");
      }
      printValue(e.getValue());
    }
    builder.append(')');
  }
  return null;
}
 
Example 4
Source Project: openjdk-jdk9   Source File: DPrinter.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void printObject(String label, Object item, Details details) {
    if (item == null) {
        printNull(label);
    } else if (item instanceof Attribute) {
        printAttribute(label, (Attribute) item);
    } else if (item instanceof Symbol) {
        printSymbol(label, (Symbol) item, details);
    } else if (item instanceof Type) {
        printType(label, (Type) item, details);
    } else if (item instanceof JCTree) {
        printTree(label, (JCTree) item);
    } else if (item instanceof DocTree) {
        printDocTree(label, (DocTree) item);
    } else if (item instanceof List) {
        printList(label, (List) item);
    } else if (item instanceof Name) {
        printName(label, (Name) item);
    } else if (item instanceof Scope) {
        printScope(label, (Scope) item);
    } else {
        printString(label, String.valueOf(item));
    }
}
 
Example 5
Source Project: TencentKona-8   Source File: DPrinter.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void printObject(String label, Object item, Details details) {
    if (item == null) {
        printNull(label);
    } else if (item instanceof Attribute) {
        printAttribute(label, (Attribute) item);
    } else if (item instanceof Symbol) {
        printSymbol(label, (Symbol) item, details);
    } else if (item instanceof Type) {
        printType(label, (Type) item, details);
    } else if (item instanceof JCTree) {
        printTree(label, (JCTree) item);
    } else if (item instanceof List) {
        printList(label, (List) item);
    } else if (item instanceof Name) {
        printName(label, (Name) item);
    } else {
        printString(label, String.valueOf(item));
    }
}
 
Example 6
Source Project: jdk8u60   Source File: DocCommentTester.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
    void check(TreePath path, Name name) throws Exception {
        String raw = trees.getDocComment(path);
        String normRaw = normalize(raw);

        StringWriter out = new StringWriter();
        DocPretty dp = new DocPretty(out);
        dp.print(trees.getDocCommentTree(path));
        String pretty = out.toString();

        if (!pretty.equals(normRaw)) {
            error("mismatch");
            System.err.println("*** expected:");
            System.err.println(normRaw.replace(" ", "_"));
            System.err.println("*** found:");
            System.err.println(pretty.replace(" ", "_"));
//            throw new Error();
        }
    }
 
Example 7
Source Project: auto   Source File: EclipseHack.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a map containing the real return types of the given methods, knowing that they appear
 * in the given type. This means that if the given type is say {@code StringIterator implements
 * Iterator<String>} then we want the {@code next()} method to map to String, rather than the
 * {@code T} that it returns as inherited from {@code Iterator<T>}. This method is in EclipseHack
 * because if it weren't for <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=382590">this
 * Eclipse bug</a> it would be trivial. Unfortunately, versions of Eclipse up to at least 4.5 have
 * a bug where the {@link Types#asMemberOf} method throws IllegalArgumentException if given a
 * method that is inherited from an interface. Fortunately, Eclipse's implementation of {@link
 * Elements#getAllMembers} does the type substitution that {@code asMemberOf} would have done. But
 * javac's implementation doesn't. So we try the way that would work if Eclipse weren't buggy, and
 * only if we get IllegalArgumentException do we use {@code getAllMembers}.
 */
ImmutableMap<ExecutableElement, TypeMirror> methodReturnTypes(
    Set<ExecutableElement> methods, DeclaredType in) {
  ImmutableMap.Builder<ExecutableElement, TypeMirror> map = ImmutableMap.builder();
  Map<Name, ExecutableElement> noArgMethods = null;
  for (ExecutableElement method : methods) {
    TypeMirror returnType = null;
    try {
      TypeMirror methodMirror = typeUtils.asMemberOf(in, method);
      returnType = MoreTypes.asExecutable(methodMirror).getReturnType();
    } catch (IllegalArgumentException e) {
      if (method.getParameters().isEmpty()) {
        if (noArgMethods == null) {
          noArgMethods = noArgMethodsIn(in);
        }
        returnType = noArgMethods.get(method.getSimpleName()).getReturnType();
      }
    }
    if (returnType == null) {
      returnType = method.getReturnType();
    }
    map.put(method, returnType);
  }
  return map.build();
}
 
Example 8
Source Project: turbine   Source File: TurbineElementsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getName() {
  Name n = turbineElements.getName("hello");
  assertThat(n.contentEquals("hello")).isTrue();
  assertThat(n.contentEquals("goodbye")).isFalse();

  assertThat(n.toString()).isEqualTo("hello");
  assertThat(n.toString())
      .isEqualTo(new String(new char[] {'h', 'e', 'l', 'l', 'o'})); // defeat interning

  assertThat(n.length()).isEqualTo(5);

  new EqualsTester()
      .addEqualityGroup(turbineElements.getName("hello"), turbineElements.getName("hello"))
      .addEqualityGroup(turbineElements.getName("goodbye"))
      .testEquals();
}
 
Example 9
Source Project: RADL   Source File: AbstractRestAnnotationProcessor.java    License: Apache License 2.0 5 votes vote down vote up
protected Collection<String> valueOf(TypeElement annotation, Element element, String property) {
  if (annotation == null) {
    return null;
  }
  Name annotationClassName = annotation.getQualifiedName();
  for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
    TypeElement annotationElement = (TypeElement)annotationMirror.getAnnotationType().asElement();
    if (annotationElement.getQualifiedName().contentEquals(annotationClassName)) {
      return valueOf(annotationMirror, property);
    }
  }
  return null;
}
 
Example 10
Source Project: openjdk-8   Source File: LLNI.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected final boolean needLongName(ExecutableElement method,
                                     TypeElement clazz) {
    Name methodName = method.getSimpleName();
    for (ExecutableElement memberMethod: methods) {
        if ((memberMethod != method) &&
            memberMethod.getModifiers().contains(Modifier.NATIVE) &&
                (methodName.equals(memberMethod.getSimpleName())))
            return true;
    }
    return false;
}
 
Example 11
@Override
public Name getQualifiedName() {
	ReferenceBinding binding = (ReferenceBinding)_binding;
	char[] qName;
	if (binding.isMemberType()) {
		qName = CharOperation.concatWith(binding.enclosingType().compoundName, binding.sourceName, '.');
		CharOperation.replace(qName, '$', '.');
	} else {
		qName = CharOperation.concatWith(binding.compoundName, '.');
	}
	return new NameImpl(qName);
}
 
Example 12
Source Project: immutables   Source File: Styles.java    License: Apache License 2.0 5 votes vote down vote up
public final boolean possibleAttributeBuilder(Name name) {
  for (Naming pattern : scheme.attributeBuilder) {
    String foundPattern = pattern.detect(name.toString());
    if (!foundPattern.isEmpty()) {
      return true;
    }
  }
  return false;
}
 
Example 13
Source Project: FreeBuilder   Source File: JavacMethodIntrospector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Set<Name> getOwnMethodInvocations(ExecutableElement method) {
  try {
    return ImmutableSet.copyOf(trees
        .getTree(method)
        .accept(OWN_METHOD_INVOCATIONS_FETCHER, null)
        .names);
  } catch (RuntimeException e) {
    // Fail gracefully
    return ImmutableSet.of();
  }
}
 
Example 14
Source Project: flo   Source File: ApiGeneratorProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void writeApiInterface(
    GenerateTaskBuilder genTaskBuilder,
    Name packageName,
    String interfaceName) throws IOException {

  final Map<String, Object> data = new HashMap<>();
  data.put("packageName", packageName);
  data.put("interfaceName", interfaceName);
  data.put("genFn", IntStream.rangeClosed(0, genTaskBuilder.upTo())
      .mapToObj(this::fn).toArray());
  data.put("genBuilder", IntStream.range(1, genTaskBuilder.upTo())
      .mapToObj(this::builder).toArray());
  final String output = engine.getMustache("TaskBuilder").render(data);
  final String outputScala = engine.getMustache("ScalaApi").render(data);

  if (!genTaskBuilder.scala()) {
    final String fileName = packageName + "." + interfaceName;
    final JavaFileObject filerSourceFile = filer.createSourceFile(fileName, processingElement);
    try (final Writer writer = filerSourceFile.openWriter()) {
      writer.write(output);
    }
  } else {
    final FileObject scalaFile = filer.createResource(
        StandardLocation.SOURCE_OUTPUT, packageName, "ScalaApi.scala", processingElement);
    try (final Writer writer = scalaFile.openWriter()) {
      writer.write(outputScala);
    }
  }
}
 
Example 15
private boolean fillFirstArgument(
        ExpressionTree e,
        List<ExpressionTree> items,
        Indent indent) {
    // is there a trailing dereference?
    if (items.size() < 2) {
        return false;
    }
    // don't special-case calls nested inside expressions
    if (e.getKind() != METHOD_INVOCATION) {
        return false;
    }
    MethodInvocationTree methodInvocation = (MethodInvocationTree) e;
    Name name = getMethodName(methodInvocation);
    if (!(methodInvocation.getMethodSelect() instanceof IdentifierTree)
            || name.length() > 4
            || !methodInvocation.getTypeArguments().isEmpty()
            || methodInvocation.getArguments().size() != 1) {
        return false;
    }
    builder.open(ZERO);
    builder.open(indent);
    visit(name);
    token("(");
    ExpressionTree arg = getOnlyElement(methodInvocation.getArguments());
    scan(arg, null);
    builder.close();
    token(")");
    builder.close();
    return true;
}
 
Example 16
private void checkValue(String type, Name elementName, String expected, String actual) {
  if (expected != actual && (expected == null || !expected.equals(actual))) {
    errors.add(
        String.format(
            "%s %s:\n\tExpected: %s\n\tActual: %s", type, elementName, expected, actual));
  }
}
 
Example 17
@Override
void check(TreePath path, Name name) throws Exception {
    JavaFileObject fo = path.getCompilationUnit().getSourceFile();
    final CharSequence cs = fo.getCharContent(true);

    final DCDocComment dc = (DCDocComment) trees.getDocCommentTree(path);
    DCTree t = (DCTree) trees.getDocCommentTree(path);

    DocTreeScanner scanner = new DocTreeScanner<Void,Void>() {
        @Override
        public Void scan(DocTree node, Void ignore) {
            if (node != null) {
                try {
                    String expect = getExpectText(node);
                    long pos = ((DCTree) node).getSourcePosition(dc);
                    String found = getFoundText(cs, (int) pos, expect.length());
                    if (!found.equals(expect)) {
                        System.err.println("expect: " + expect);
                        System.err.println("found:  " + found);
                        error("mismatch");
                    }

                } catch (StringIndexOutOfBoundsException e) {
                    error(node.getClass() + ": " + e.toString());
                        e.printStackTrace();
                }
            }
            return super.scan(node, ignore);
        }
    };

    scanner.scan(t, null);
}
 
Example 18
Source Project: netbeans   Source File: ReferenceTransformer.java    License: Apache License 2.0 5 votes vote down vote up
private void handleIdentifier(Tree node, Name id) {
    TreeMaker mk = copy.getTreeMaker();
    String nn = id.toString();
    if (nn.equals(name)) {
        Element res = copy.getTrees().getElement(getCurrentPath());
        if (res != null && res == shadowed) {
            if (res.getModifiers().contains(Modifier.STATIC)) {
                copy.rewrite(node, 
                        mk.MemberSelect(
                            mk.Identifier(shadowedGate), // NOI18N
                            res.getSimpleName().toString()
                        )
                );
            } else if (shadowedGate == target) {
                copy.rewrite(node, 
                        mk.MemberSelect(
                            mk.MemberSelect(mk.Identifier(target), "super"), // NOI18N
                            res.getSimpleName().toString()
                        )
                );
            } else {
                copy.rewrite(node, 
                        mk.MemberSelect(
                            mk.MemberSelect(mk.Identifier(shadowedGate), "this"), // NOI18N
                            res.getSimpleName().toString()
                        )
                );
            }
        }
    }
}
 
Example 19
Source Project: jdk8u60   Source File: LLNI.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected final boolean needLongName(ExecutableElement method,
                                     TypeElement clazz) {
    Name methodName = method.getSimpleName();
    for (ExecutableElement memberMethod: methods) {
        if ((memberMethod != method) &&
            memberMethod.getModifiers().contains(Modifier.NATIVE) &&
                (methodName.equals(memberMethod.getSimpleName())))
            return true;
    }
    return false;
}
 
Example 20
Source Project: netbeans   Source File: Util.java    License: Apache License 2.0 5 votes vote down vote up
protected static boolean containsName(String[] stringNames, Name name) {
    for (String stringName : stringNames) {
        if (name.contentEquals(stringName)) {
            return true;
        }
    }
    return false;
}
 
Example 21
Source Project: netbeans   Source File: Flow.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns an alias for the Element, if the undefined name was already found. Returns e
 * and causes further names like 'e' to be aliased to e instance. This cannonicalization is
 * used to support collection operations throughout the flow
 */
private Element canonicalUndefined(Element e) {
    Name n = e.getSimpleName();
    Element prev = undefinedVariables.get(n);
    if (prev != null) {
        return prev;
    } else {
        undefinedVariables.put(n, e);
        return e;
    }
}
 
Example 22
Source Project: annotation-tools   Source File: AMethod.java    License: MIT License 5 votes vote down vote up
/**
 * Populates the method parameter map for the method.
 * Ensures that the method parameter map always has an entry for each parameter.
 *
 * @param methodElt the method whose parameters should be vivified
 */
private void vivifyAndAddTypeMirrorToParameters(ExecutableElement methodElt) {
    for (int i = 0; i < methodElt.getParameters().size(); i++) {
        VariableElement ve = methodElt.getParameters().get(i);
        TypeMirror type = ve.asType();
        Name name = ve.getSimpleName();
        vivifyAndAddTypeMirrorToParameter(i, type, name);
    }
}
 
Example 23
Source Project: buck   Source File: BridgeMethods.java    License: Apache License 2.0 5 votes vote down vote up
public List<BridgeMethod> getBridgeMethodsNoCreate(TypeElement typeElement, Name name) {
  if (allBridgeMethods.containsKey(typeElement)) {
    return getBridgeMethods(typeElement, name);
  }

  return Collections.emptyList();
}
 
Example 24
public SeiContext getSeiContext(Name seiName) {
    SeiContext context = seiContextMap.get(seiName);
    if (context == null) {
        context = new SeiContext();
        addSeiContext(seiName, context);
    }
    return context;
}
 
Example 25
Source Project: netbeans   Source File: GeneratorUtilities.java    License: 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 26
Source Project: netbeans   Source File: EventInjectionPointLogic.java    License: Apache License 2.0 5 votes vote down vote up
private List<VariableElement> getEventInjectionPoints( )
{
    final List<VariableElement> eventInjection = new LinkedList<VariableElement>();
    try {
        getModel().getHelper().getAnnotationScanner().findAnnotations(INJECT_ANNOTATION, 
                EnumSet.of( ElementKind.FIELD),  new AnnotationHandler() {
                    
                    @Override
                    public void handleAnnotation( TypeElement type, 
                            Element element, AnnotationMirror annotation )
                    {
                       Element typeElement = getCompilationController().getTypes().
                               asElement( element.asType() );
                        if ( typeElement instanceof TypeElement && 
                                element instanceof VariableElement )
                        {
                            Name name = ((TypeElement)typeElement).getQualifiedName();
                            if ( EVENT_INTERFACE.contentEquals( name )){
                                eventInjection.add( (VariableElement) element);
                            }
                        }
                    }
                });
    }
    catch (InterruptedException e) {
        LOGGER.warning("Finding annotation @Inject was interrupted"); // NOI18N
    }
    return eventInjection;
}
 
Example 27
Source Project: revapi   Source File: MissingTypeElement.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Name getQualifiedName() {
    return new NameImpl(qualifiedName);
}
 
Example 28
void visitDecl(Tree tree, Name name) {
    TreePath path = getCurrentPath();
    DocCommentTree dc = trees.getDocCommentTree(path);
    if (dc != null)
        cs.scan(new DocTreePath(path, dc), null);
}
 
Example 29
Source Project: turbine   Source File: TurbineElement.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Name getSimpleName() {
  return new TurbineName(info().sym().name());
}
 
Example 30
Source Project: netbeans   Source File: StaticAccess.java    License: Apache License 2.0 4 votes vote down vote up
protected static Fix computeFixes(CompilationInfo info, TreePath treePath, int[] bounds, int[] kind, String[] simpleName) {
    if (treePath.getLeaf().getKind() != Kind.MEMBER_SELECT) {
        return null;
    }
    MemberSelectTree mst = (MemberSelectTree)treePath.getLeaf();
    Tree expression = mst.getExpression();
    TreePath expr = new TreePath(treePath, expression);
    
    TypeMirror tm = info.getTrees().getTypeMirror(expr);
    if (!Utilities.isValidType(tm)) {
        return null;
    }
    Element el = info.getTypes().asElement(tm);
    if (el == null || (!el.getKind().isClass() && !el.getKind().isInterface())) {
        return null;
    }
    
    TypeElement type = (TypeElement)el;
    
    if (isError(type)) {
        return null;
    }
    
    Name idName = null;
    
    if (expression.getKind() == Kind.MEMBER_SELECT) {
        MemberSelectTree exprSelect = (MemberSelectTree)expression;
        idName = exprSelect.getIdentifier();
    }
    
    if (expression.getKind() == Kind.IDENTIFIER) {
        IdentifierTree idt = (IdentifierTree)expression;
        idName = idt.getName();
    }
    
    if (idName != null) {
        if (idName.equals(type.getSimpleName())) {
            return null;
        }
        if (idName.equals(type.getQualifiedName())) {
            return null;
        }
    }
    
    Element used = info.getTrees().getElement(treePath);
    
    if (used == null || !used.getModifiers().contains(Modifier.STATIC)) {
        return null;
    }
    
    if (isError(used)) {
        return null;
    }
    
    if (used.getKind().isField()) {
        kind[0] = 0;
    } else {
        if (used.getKind() == ElementKind.METHOD) {
            kind[0] = 1;
        } else {
            kind[0] = 2;
        }
    }
    
    simpleName[0] = used.getSimpleName().toString();
    
    return new FixImpl(info, expr, type).toEditorFix();
}