javax.lang.model.element.Name Java Examples

The following examples show how to use javax.lang.model.element.Name. 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: DPrinter.java    From openjdk-jdk9 with 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 #2
Source File: AnnotationMirrors.java    From immutables with 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 #3
Source File: FitProcessor.java    From fit with 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 #4
Source File: EntityClassInfo.java    From netbeans with 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 #5
Source File: DPrinter.java    From TencentKona-8 with 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 File: DocCommentTester.java    From jdk8u60 with 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 File: EclipseHack.java    From auto with 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 File: TurbineElementsTest.java    From turbine with 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 File: ErrorTypeElement.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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 #10
Source File: ApiGeneratorProcessor.java    From flo with 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 #11
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 #12
Source File: AMethod.java    From annotation-tools with 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 #13
Source File: Util.java    From netbeans with 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 #14
Source File: AnnotationProcessorContext.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public SeiContext getSeiContext(Name seiName) {
    SeiContext context = seiContextMap.get(seiName);
    if (context == null) {
        context = new SeiContext();
        addSeiContext(seiName, context);
    }
    return context;
}
 
Example #15
Source File: LLNI.java    From openjdk-8 with 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 #16
Source File: BridgeMethods.java    From buck with 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 #17
Source File: Flow.java    From netbeans with 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 #18
Source File: JavacMethodIntrospector.java    From FreeBuilder with 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 #19
Source File: EventInjectionPointLogic.java    From netbeans with 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 #20
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: DescriptorAndSignatureFactoryTestBase.java    From buck with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: LLNI.java    From jdk8u60 with 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 #23
Source File: ReferenceTransformer.java    From netbeans with 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 #24
Source File: DocCommentTester.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@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 #25
Source File: AbstractRestAnnotationProcessor.java    From RADL with 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 #26
Source File: Styles.java    From immutables with 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 #27
Source File: ComponentGenerator.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
private void writeInterfaceMethods(BindingGraph input, ClassWriter componentWriter,
    ImmutableMap<BindingKey, MemberSelect> memberSelectSnippets,
    ImmutableSet<BindingKey> enumBindingKeys) throws AssertionError {
  Set<MethodSignature> interfaceMethods = Sets.newHashSet();

  for (ComponentMethodDescriptor componentMethod :
      input.componentDescriptor().componentMethods()) {
    if (componentMethod.dependencyRequest().isPresent()) {
      DependencyRequest interfaceRequest = componentMethod.dependencyRequest().get();
      ExecutableElement requestElement =
          MoreElements.asExecutable(interfaceRequest.requestElement());
      ExecutableType requestType = MoreTypes.asExecutable(types.asMemberOf(
          MoreTypes.asDeclared(input.componentDescriptor().componentDefinitionType().asType()),
          requestElement));
      MethodSignature signature = MethodSignature.fromExecutableType(
          requestElement.getSimpleName().toString(),
          requestType);
      if (!interfaceMethods.contains(signature)) {
        interfaceMethods.add(signature);
        MethodWriter interfaceMethod = requestType.getReturnType().getKind().equals(VOID)
            ? componentWriter.addMethod(VoidName.VOID, requestElement.getSimpleName().toString())
                : componentWriter.addMethod(requestType.getReturnType(),
                    requestElement.getSimpleName().toString());
        interfaceMethod.annotate(Override.class);
        interfaceMethod.addModifiers(PUBLIC);
        BindingKey bindingKey = interfaceRequest.bindingKey();
        switch(interfaceRequest.kind()) {
          case MEMBERS_INJECTOR:
            MemberSelect membersInjectorSelect = memberSelectSnippets.get(bindingKey);
            List<? extends VariableElement> parameters = requestElement.getParameters();
            if (parameters.isEmpty()) {
              // we're returning the framework type
              interfaceMethod.body().addSnippet("return %s;",
                  membersInjectorSelect.getSnippetFor(componentWriter.name()));
            } else {
              VariableElement parameter = Iterables.getOnlyElement(parameters);
              Name parameterName = parameter.getSimpleName();
              interfaceMethod.addParameter(
                  TypeNames.forTypeMirror(
                      Iterables.getOnlyElement(requestType.getParameterTypes())),
                  parameterName.toString());
              interfaceMethod.body().addSnippet("%s.injectMembers(%s);",
                  // in this case we know we won't need the cast because we're never going to pass
                  // the reference to anything
                  membersInjectorSelect.getSnippetFor(componentWriter.name()),
                  parameterName);
              if (!requestType.getReturnType().getKind().equals(VOID)) {
                interfaceMethod.body().addSnippet("return %s;", parameterName);
              }
            }
            break;
          case INSTANCE:
            if (enumBindingKeys.contains(bindingKey)
                && !MoreTypes.asDeclared(bindingKey.key().type())
                        .getTypeArguments().isEmpty()) {
              // If using a parameterized enum type, then we need to store the factory
              // in a temporary variable, in order to help javac be able to infer
              // the generics of the Factory.create methods.
              TypeName factoryType = ParameterizedTypeName.create(Provider.class,
                  TypeNames.forTypeMirror(requestType.getReturnType()));
              interfaceMethod.body().addSnippet("%s factory = %s;", factoryType,
                  memberSelectSnippets.get(bindingKey).getSnippetFor(componentWriter.name()));
              interfaceMethod.body().addSnippet("return factory.get();");
              break;
            }
            // fall through in the else case.
          case LAZY:
          case PRODUCED:
          case PRODUCER:
          case PROVIDER:
          case FUTURE:
            interfaceMethod.body().addSnippet("return %s;",
                frameworkTypeUsageStatement(
                    memberSelectSnippets.get(bindingKey).getSnippetFor(componentWriter.name()),
                    interfaceRequest.kind()));
            break;
          default:
            throw new AssertionError();
        }
      }
    }
  }
}
 
Example #28
Source File: AbstractRestAnnotationProcessorTest.java    From RADL with Apache License 2.0 4 votes vote down vote up
protected Name name(String value) {
  return new TestName(value);
}
 
Example #29
Source File: DescriptorAndSignatureFactoryTestBase.java    From buck with Apache License 2.0 4 votes vote down vote up
private MethodNode getMethodNode(ClassNode classNode, Name name) {
  return classNode.methods.stream()
      .filter(field -> name.contentEquals(field.name))
      .findFirst()
      .orElse(null);
}
 
Example #30
Source File: WebServiceAp.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String getOperationName(Name messageName) {
    return messageName != null ? messageName.toString() : null;
}