Java Code Examples for javax.lang.model.element.TypeElement#getQualifiedName()

The following examples show how to use javax.lang.model.element.TypeElement#getQualifiedName() . 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: EntityPropertyMetaFactory.java    From doma with Apache License 2.0 6 votes vote down vote up
private void validateSequenceIdGenerator(
    EntityPropertyMeta propertyMeta, SequenceGeneratorAnnot sequenceGeneratorAnnot) {
  TypeElement typeElement =
      ctx.getMoreTypes().toTypeElement(sequenceGeneratorAnnot.getImplementerValue());
  if (typeElement == null) {
    throw new AptIllegalStateException("failed to convert to TypeElement");
  }
  if (typeElement.getModifiers().contains(Modifier.ABSTRACT)) {
    throw new AptException(
        Message.DOMA4170,
        fieldElement,
        sequenceGeneratorAnnot.getAnnotationMirror(),
        sequenceGeneratorAnnot.getImplementer(),
        new Object[] {typeElement.getQualifiedName()});
  }
  ExecutableElement constructor = ctx.getMoreElements().getNoArgConstructor(typeElement);
  if (constructor == null || !constructor.getModifiers().contains(Modifier.PUBLIC)) {
    throw new AptException(
        Message.DOMA4171,
        fieldElement,
        sequenceGeneratorAnnot.getAnnotationMirror(),
        sequenceGeneratorAnnot.getImplementer(),
        new Object[] {typeElement.getQualifiedName()});
  }
}
 
Example 2
Source File: EntityMetaFactory.java    From doma with Apache License 2.0 6 votes vote down vote up
void validateFieldAnnotation(VariableElement fieldElement, EntityMeta entityMeta) {
  TypeElement foundAnnotationTypeElement = null;
  for (AnnotationMirror annotation : fieldElement.getAnnotationMirrors()) {
    DeclaredType declaredType = annotation.getAnnotationType();
    TypeElement typeElement = ctx.getMoreTypes().toTypeElement(declaredType);
    if (typeElement.getAnnotation(EntityField.class) != null) {
      if (foundAnnotationTypeElement != null) {
        throw new AptException(
            Message.DOMA4086,
            fieldElement,
            new Object[] {
              foundAnnotationTypeElement.getQualifiedName(), typeElement.getQualifiedName(),
            });
      }
      foundAnnotationTypeElement = typeElement;
    }
  }
}
 
Example 3
Source File: GwtCompatibility.java    From SimpleWeibo with Apache License 2.0 6 votes vote down vote up
String gwtCompatibleAnnotationString() {
  if (gwtCompatibleAnnotation.isPresent()) {
    AnnotationMirror annotation = gwtCompatibleAnnotation.get();
    TypeElement annotationElement = (TypeElement) annotation.getAnnotationType().asElement();
    String annotationArguments;
    if (annotation.getElementValues().isEmpty()) {
      annotationArguments = "";
    } else {
      List<String> elements = Lists.newArrayList();
      for (Map.Entry<ExecutableElement, AnnotationValue> entry :
          Collections.unmodifiableMap(annotation.getElementValues()).entrySet()) {
        elements.add(entry.getKey().getSimpleName() + " = " + entry.getValue());
      }
      annotationArguments = "(" + Joiner.on(", ").join(elements) + ")";
    }
    return "@" + annotationElement.getQualifiedName() + annotationArguments;
  } else {
    return "";
  }
}
 
Example 4
Source File: ArgProcessor.java    From fragmentargs with Apache License 2.0 6 votes vote down vote up
/**
 * Scans a fragment for a given {@link FragmentWithArgs} annotation
 *
 * @param env             The round environment
 * @param annotationClass The annotation (.class) to scan for
 * @param fragmentClasses The set of classes already scanned (containing annotations)
 * @throws ProcessingException
 */
private void scanForAnnotatedFragmentClasses(RoundEnvironment env,
                                             Class<? extends Annotation> annotationClass, Set<TypeElement> fragmentClasses,
                                             Element element)
        throws ProcessingException {

    if (element.getKind() != ElementKind.CLASS) {
        throw new ProcessingException(element, "%s can only be applied on Fragment classes",
                annotationClass.getSimpleName());
    }

    TypeElement classElement = (TypeElement) element;

    // Check if its a fragment
    if (!isFragmentClass(element)) {
        throw new ProcessingException(element,
                "%s can only be used on fragments, but %s is not a subclass of fragment",
                annotationClass.getSimpleName(), classElement.getQualifiedName());
    }

    // Skip abstract classes
    if (!classElement.getModifiers().contains(Modifier.ABSTRACT)) {
        fragmentClasses.add(classElement);
    }
}
 
Example 5
Source File: ReplaceBufferByString.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean visitNewClass(NewClassTree node, Void p) {
    TypeMirror tm = ci.getTrees().getTypeMirror(getCurrentPath());
    if (tm == null || tm.getKind() != TypeKind.DECLARED) {
        return false;
    }
    TypeElement el = (TypeElement)((DeclaredType)tm).asElement();
    if (el == null) {
        return false;
    }
    Name n = el.getQualifiedName();
    boolean res = n.contentEquals("java.lang.StringBuilder") || n.contentEquals("java.lang.StringBuffer"); // NOI18N
    // check if there is some initial contents
    if (node.getArguments().size() == 1 && 
            Utilities.isJavaString(ci, ci.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getArguments().get(0))))) {
        hasContents = true;
    }
    return res;
}
 
Example 6
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Determines if the element corresponds to never-returning, terminating method.
 * System.exit, Runtime.exit, Runtime.halt are checked. The passed element is
 * usually a result of {@code CompilationInfo.getTrees().getElement(path)}.
 * 
 * @param info context
 * @param e element to check
 * @return true, if the element corrresponds to a VM-exiting method
 */
public static boolean isSystemExit(CompilationInfo info, Element e) {
    if (e == null || e.getKind() != ElementKind.METHOD) {
        return false;
    }
    ExecutableElement ee = (ExecutableElement)e;
    Name n = ee.getSimpleName();
    if (n.contentEquals("exit") || n.contentEquals("halt")) { // NOI18N
        TypeElement tel = info.getElementUtilities().enclosingTypeElement(e);
        if (tel == null) {
            return false;
        }
        Name ofqn = tel.getQualifiedName();
        if (ofqn.contentEquals("java.lang.System") || ofqn.contentEquals("java.lang.Runtime")) { // NOI18N
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: ClassEntity.java    From RxPay with Apache License 2.0 6 votes vote down vote up
/**
 * @param elementUtils
 * @param typeUtils
 * @param element      current anntated class
 */
public ClassEntity(Elements elementUtils, Types typeUtils, TypeElement element) {
    elementWeakCache = new WeakReference<TypeElement>(element);
    this.classPackageName = elementUtils.getPackageOf(element).getQualifiedName().toString();
    this.modifierSet = element.getModifiers();
    this.className = element.toString();
    annotationMirrors = element.getAnnotationMirrors();
    this.classSimpleName = element.getSimpleName();
    this.classQualifiedName = element.getQualifiedName();
    if ("java.lang.Object".equals(element.getSuperclass().toString())){
        this.superclass = null;
    }else{
        this.superclass = element.getSuperclass().toString();
    }
    List<? extends TypeMirror> interfaces = element.getInterfaces();

    for (TypeMirror anInterface : interfaces){
        this.interfaces.add(typeUtils.asElement(anInterface).toString());
    }
}
 
Example 8
Source File: MethodTranslator.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private ExecutableElement findConstructor(TypeElement type, MethodReference methodDef) {
  String signature = methodDef.getSignature();
  String erasedSignature = methodDef.getErasedSignature();
  for (Element e : type.getEnclosedElements()) {
    if (e.getKind() == ElementKind.CONSTRUCTOR) {
      String sig = typeUtil.getReferenceSignature((ExecutableElement) e);
      if (sig.equals(signature) || sig.equals(erasedSignature)) {
        return (ExecutableElement) e;
      }
    }
  }
  throw new AssertionError("failed constructor lookup: " + type.getQualifiedName() + signature);
}
 
Example 9
Source File: EntityMetaFactory.java    From doma with Apache License 2.0 5 votes vote down vote up
void validateInheritedEntityListener(
    TypeElement classElement, EntityMeta entityMeta, TypeElement inheritedListenerElement) {
  EntityAnnot entityAnnot = entityMeta.getEntityAnnot();
  List<? extends TypeParameterElement> typeParams =
      inheritedListenerElement.getTypeParameters();
  if (typeParams.size() == 0) {
    throw new AptException(
        Message.DOMA4230,
        classElement,
        entityAnnot.getAnnotationMirror(),
        new Object[] {
          inheritedListenerElement.getQualifiedName(), classElement.getQualifiedName()
        });
  }
  TypeParameterElement typeParam = typeParams.get(0);
  for (TypeMirror bound : typeParam.getBounds()) {
    if (!ctx.getMoreTypes().isAssignableWithErasure(classElement.asType(), bound)) {
      throw new AptException(
          Message.DOMA4231,
          classElement,
          entityAnnot.getAnnotationMirror(),
          new Object[] {
            inheritedListenerElement.getQualifiedName(),
            typeParam.getSimpleName(),
            bound,
            classElement.getQualifiedName()
          });
    }
  }
}
 
Example 10
Source File: ValueAttribute.java    From immutables with Apache License 2.0 5 votes vote down vote up
private @Nullable NullabilityAnnotationInfo isAccessorNullableAccessor(Element element) {
  for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
    TypeElement annotationElement = (TypeElement) annotation.getAnnotationType().asElement();
    Name simpleName = annotationElement.getSimpleName();
    Name qualifiedName = annotationElement.getQualifiedName();
    if (isNullableAnnotation(simpleName, qualifiedName)) {
      return ImmutableNullabilityAnnotationInfo.of(annotationElement);
    }
  }
  return null;
}
 
Example 11
Source File: AutoServiceProcessor.java    From auto with Apache License 2.0 5 votes vote down vote up
private void processAnnotations(Set<? extends TypeElement> annotations,
    RoundEnvironment roundEnv) {

  Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(AutoService.class);

  log(annotations.toString());
  log(elements.toString());

  for (Element e : elements) {
    // TODO(gak): check for error trees?
    TypeElement providerImplementer = (TypeElement) e;
    AnnotationMirror annotationMirror = getAnnotationMirror(e, AutoService.class).get();
    Set<DeclaredType> providerInterfaces = getValueFieldOfClasses(annotationMirror);
    if (providerInterfaces.isEmpty()) {
      error(MISSING_SERVICES_ERROR, e, annotationMirror);
      continue;
    }
    for (DeclaredType providerInterface : providerInterfaces) {
      TypeElement providerType = MoreTypes.asTypeElement(providerInterface);

      log("provider interface: " + providerType.getQualifiedName());
      log("provider implementer: " + providerImplementer.getQualifiedName());

      if (checkImplementer(providerImplementer, providerType)) {
        providers.put(getBinaryName(providerType), getBinaryName(providerImplementer));
      } else {
        String message = "ServiceProviders must implement their service provider interface. "
            + providerImplementer.getQualifiedName() + " does not implement "
            + providerType.getQualifiedName();
        error(message, e, annotationMirror);
      }
    }
  }
}
 
Example 12
Source File: AutoCodecProcessor.java    From bazel with Apache License 2.0 5 votes vote down vote up
private MethodSpec buildSerializeMethodWithInstantiator(
    TypeElement encodedType, List<? extends VariableElement> fields, AutoCodec annotation)
    throws SerializationProcessingFailedException {
  MethodSpec.Builder serializeBuilder =
      AutoCodecUtil.initializeSerializeMethodBuilder(encodedType, annotation, env);
  for (VariableElement parameter : fields) {
    Optional<FieldValueAndClass> hasField =
        getFieldByNameRecursive(encodedType, parameter.getSimpleName().toString());
    if (hasField.isPresent()) {
      if (findRelationWithGenerics(hasField.get().value.asType(), parameter.asType())
          == Relation.UNRELATED_TO) {
        throw new SerializationProcessingFailedException(
            parameter,
            "%s: parameter %s's type %s is unrelated to corresponding field type %s",
            encodedType.getQualifiedName(),
            parameter.getSimpleName(),
            parameter.asType(),
            hasField.get().value.asType());
      }
      TypeKind typeKind = parameter.asType().getKind();
      serializeBuilder.addStatement(
          "$T unsafe_$L = ($T) $T.getInstance().get$L(input, $L_offset)",
          sanitizeTypeParameter(parameter.asType(), env),
          parameter.getSimpleName(),
          sanitizeTypeParameter(parameter.asType(), env),
          UnsafeProvider.class,
          typeKind.isPrimitive() ? firstLetterUpper(typeKind.toString().toLowerCase()) : "Object",
          parameter.getSimpleName());
          marshallers.writeSerializationCode(
              new Marshaller.Context(
                  serializeBuilder, parameter.asType(), "unsafe_" + parameter.getSimpleName()));
    } else {
      addSerializeParameterWithGetter(encodedType, parameter, serializeBuilder);
    }
  }
  return serializeBuilder.build();
}
 
Example 13
Source File: InternalDomainMetaFactory.java    From doma with Apache License 2.0 5 votes vote down vote up
void validateEnclosingElement(Element element) {
  TypeElement typeElement = ctx.getMoreElements().toTypeElement(element);
  if (typeElement == null) {
    return;
  }
  String simpleName = typeElement.getSimpleName().toString();
  if (simpleName.contains(Constants.BINARY_NAME_DELIMITER)
      || simpleName.contains(Constants.TYPE_NAME_DELIMITER)) {
    throw new AptException(
        Message.DOMA4277, typeElement, new Object[] {typeElement.getQualifiedName()});
  }
  NestingKind nestingKind = typeElement.getNestingKind();
  if (nestingKind == NestingKind.TOP_LEVEL) {
    return;
  } else if (nestingKind == NestingKind.MEMBER) {
    Set<Modifier> modifiers = typeElement.getModifiers();
    if (modifiers.containsAll(Arrays.asList(Modifier.STATIC, Modifier.PUBLIC))) {
      validateEnclosingElement(typeElement.getEnclosingElement());
    } else {
      throw new AptException(
          Message.DOMA4275, typeElement, new Object[] {typeElement.getQualifiedName()});
    }
  } else {
    throw new AptException(
        Message.DOMA4276, typeElement, new Object[] {typeElement.getQualifiedName()});
  }
}
 
Example 14
Source File: BinderClassFactory.java    From preferencebinder with Apache License 2.0 5 votes vote down vote up
static void addDefault(String key, String defaultFieldName, String type, TypeElement enclosingElement) {
    if(defaultFieldMap.containsKey(key)){
        throw new IllegalArgumentException("Default value set more than once for \""+key);
    }

    final String qualifiedFieldCall = enclosingElement.getQualifiedName() + "." + defaultFieldName;

    defaultFieldMap.put(key, qualifiedFieldCall);
    defaultTypeMap.put(key, type);
}
 
Example 15
Source File: AbstractRestProcessor.java    From RADL with Apache License 2.0 4 votes vote down vote up
private boolean isBasicType(TypeElement type) {
  Name qualifiedName = type.getQualifiedName();
  return isBasicType(qualifiedName, "Object") || isBasicType(qualifiedName, "Enum");
}
 
Example 16
Source File: RegistrationAnnotatedClassCreator.java    From Alligator with MIT License 4 votes vote down vote up
private void checkThatIsNotAbstract(TypeElement classElement) throws ProcessingException {
	if (classElement.getModifiers().contains(Modifier.ABSTRACT)) {
		throw new ProcessingException(classElement, "The class %s is abstract. You can't annotate abstract classes with @RegisterScreen.", classElement.getQualifiedName());
	}
}
 
Example 17
Source File: JNIWriter.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
protected String defineForStatic(TypeElement c, VariableElement f) {
    CharSequence cnamedoc = c.getQualifiedName();
    CharSequence fnamedoc = f.getSimpleName();

    String cname = mangler.mangle(cnamedoc, Mangle.Type.CLASS);
    String fname = mangler.mangle(fnamedoc, Mangle.Type.FIELDSTUB);

    Assert.check(f.getModifiers().contains(Modifier.STATIC));

    if (f.getModifiers().contains(Modifier.FINAL)) {
        Object value = null;

        value = f.getConstantValue();

        if (value != null) { /* so it is a ConstantExpression */
            String constString = null;
            if ((value instanceof Integer)
                || (value instanceof Byte)
                || (value instanceof Short)) {
                /* covers byte, short, int */
                constString = value.toString() + "L";
            } else if (value instanceof Boolean) {
                constString = ((Boolean) value) ? "1L" : "0L";
            } else if (value instanceof Character) {
                Character ch = (Character) value;
                constString = String.valueOf(((int) ch) & 0xffff) + "L";
            } else if (value instanceof Long) {
                // Visual C++ supports the i64 suffix, not LL.
                if (isWindows)
                    constString = value.toString() + "i64";
                else
                    constString = value.toString() + "LL";
            } else if (value instanceof Float) {
                /* bug for bug */
                float fv = ((Float)value).floatValue();
                if (Float.isInfinite(fv))
                    constString = ((fv < 0) ? "-" : "") + "Inff";
                else
                    constString = value.toString() + "f";
            } else if (value instanceof Double) {
                /* bug for bug */
                double d = ((Double)value).doubleValue();
                if (Double.isInfinite(d))
                    constString = ((d < 0) ? "-" : "") + "InfD";
                else
                    constString = value.toString();
            }

            if (constString != null) {
                StringBuilder s = new StringBuilder("#undef ");
                s.append(cname); s.append("_"); s.append(fname); s.append(lineSep);
                s.append("#define "); s.append(cname); s.append("_");
                s.append(fname); s.append(" "); s.append(constString);
                return s.toString();
            }

        }
    }

    return null;
}
 
Example 18
Source File: JNIWriter.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
protected String defineForStatic(TypeElement c, VariableElement f) {
    CharSequence cnamedoc = c.getQualifiedName();
    CharSequence fnamedoc = f.getSimpleName();

    String cname = mangler.mangle(cnamedoc, Mangle.Type.CLASS);
    String fname = mangler.mangle(fnamedoc, Mangle.Type.FIELDSTUB);

    Assert.check(f.getModifiers().contains(Modifier.STATIC));

    if (f.getModifiers().contains(Modifier.FINAL)) {
        Object value = null;

        value = f.getConstantValue();

        if (value != null) { /* so it is a ConstantExpression */
            String constString = null;
            if ((value instanceof Integer)
                || (value instanceof Byte)
                || (value instanceof Short)) {
                /* covers byte, short, int */
                constString = value.toString() + "L";
            } else if (value instanceof Boolean) {
                constString = ((Boolean) value) ? "1L" : "0L";
            } else if (value instanceof Character) {
                Character ch = (Character) value;
                constString = String.valueOf(((int) ch) & 0xffff) + "L";
            } else if (value instanceof Long) {
                // Visual C++ supports the i64 suffix, not LL.
                if (isWindows)
                    constString = value.toString() + "i64";
                else
                    constString = value.toString() + "LL";
            } else if (value instanceof Float) {
                /* bug for bug */
                float fv = ((Float)value).floatValue();
                if (Float.isInfinite(fv))
                    constString = ((fv < 0) ? "-" : "") + "Inff";
                else
                    constString = value.toString() + "f";
            } else if (value instanceof Double) {
                /* bug for bug */
                double d = ((Double)value).doubleValue();
                if (Double.isInfinite(d))
                    constString = ((d < 0) ? "-" : "") + "InfD";
                else
                    constString = value.toString();
            }

            if (constString != null) {
                StringBuilder s = new StringBuilder("#undef ");
                s.append(cname); s.append("_"); s.append(fname); s.append(lineSep);
                s.append("#define "); s.append(cname); s.append("_");
                s.append(fname); s.append(" "); s.append(constString);
                return s.toString();
            }

        }
    }

    return null;
}
 
Example 19
Source File: ElementCheck.java    From stitch with Apache License 2.0 4 votes vote down vote up
static void checkTopLevel(TypeElement e) {
    Element element = e.getEnclosingElement();
    if (element.getKind() != ElementKind.PACKAGE) {
        throw new IllegalStateException("@Component error: " + e.getQualifiedName() + " can not be inner class!");
    }
}
 
Example 20
Source File: JNIWriter.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
protected String defineForStatic(TypeElement c, VariableElement f) {
    CharSequence cnamedoc = c.getQualifiedName();
    CharSequence fnamedoc = f.getSimpleName();

    String cname = mangler.mangle(cnamedoc, Mangle.Type.CLASS);
    String fname = mangler.mangle(fnamedoc, Mangle.Type.FIELDSTUB);

    Assert.check(f.getModifiers().contains(Modifier.STATIC));

    if (f.getModifiers().contains(Modifier.FINAL)) {
        Object value = null;

        value = f.getConstantValue();

        if (value != null) { /* so it is a ConstantExpression */
            String constString = null;
            if ((value instanceof Integer)
                || (value instanceof Byte)
                || (value instanceof Short)) {
                /* covers byte, short, int */
                constString = value.toString() + "L";
            } else if (value instanceof Boolean) {
                constString = ((Boolean) value) ? "1L" : "0L";
            } else if (value instanceof Character) {
                Character ch = (Character) value;
                constString = String.valueOf(((int) ch) & 0xffff) + "L";
            } else if (value instanceof Long) {
                // Visual C++ supports the i64 suffix, not LL.
                if (isWindows)
                    constString = value.toString() + "i64";
                else
                    constString = value.toString() + "LL";
            } else if (value instanceof Float) {
                /* bug for bug */
                float fv = ((Float)value).floatValue();
                if (Float.isInfinite(fv))
                    constString = ((fv < 0) ? "-" : "") + "Inff";
                else
                    constString = value.toString() + "f";
            } else if (value instanceof Double) {
                /* bug for bug */
                double d = ((Double)value).doubleValue();
                if (Double.isInfinite(d))
                    constString = ((d < 0) ? "-" : "") + "InfD";
                else
                    constString = value.toString();
            }

            if (constString != null) {
                StringBuilder s = new StringBuilder("#undef ");
                s.append(cname); s.append("_"); s.append(fname); s.append(lineSep);
                s.append("#define "); s.append(cname); s.append("_");
                s.append(fname); s.append(" "); s.append(constString);
                return s.toString();
            }

        }
    }

    return null;
}