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

The following examples show how to use javax.lang.model.element.TypeElement#asType() . 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: GraphBuilder.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private void handleTypeDeclaration(TreeNode node, TypeElement typeElem) {
  TypeMirror type = typeElem.asType();
  TypeNode typeNode = createNode(
      type, nameUtil.getSignature(type), getTypeDeclarationName(node, typeElem));
  if (captureInfo.needsOuterReference(typeElem)) {
    hasOuterRef.add(typeNode);
  }
  VariableElement receiverField = captureInfo.getReceiverField(typeElem);
  if (receiverField != null) {
    TypeNode receiverNode = getOrCreateNode(receiverField.asType());
    if (receiverNode != null) {
      addEdge(Edge.newReceiverClassEdge(typeNode, receiverNode));
    }
  }
  if (ElementUtil.isAnonymous(typeElem)) {
    followCaptureFields(typeElem, typeNode);
  }
}
 
Example 2
Source File: CreateEnumConstant.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public CreateEnumConstant(CompilationInfo info, String name, Set<Modifier> modifiers, TypeElement target, TypeMirror proposedType, FileObject targetFile) {
    this.name = name;
    this.inFQN = target.getQualifiedName().toString();
    this.cpInfo = info.getClasspathInfo();
    this.targetFile = targetFile;
    this.target = ElementHandle.create(target);
    if (proposedType.getKind() == TypeKind.NULL) {
        TypeElement tel = info.getElements().getTypeElement("java.lang.Object"); // NOI18N
        if (tel != null) {
            proposedType = tel.asType();
            this.proposedType = TypeMirrorHandle.create(proposedType);
        } else {
            this.proposedType = null;
        }
    } else {
        this.proposedType = TypeMirrorHandle.create(proposedType);
    }
}
 
Example 3
Source File: NPECheck.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public VisitorImpl(HintContext ctx, CompilationInfo aInfo, AtomicBoolean cancel) {
    this.ctx = ctx;
    if (ctx != null) {
        this.info = ctx.getInfo();
        this.cancelFlag = null;
    } else {
        this.info = aInfo;
        this.cancelFlag = cancel != null ? cancel : new AtomicBoolean(false);
    }

    
    this.throwableEl = this.info.getElements().getTypeElement("java.lang.Throwable"); // NOI18N
    TypeElement tel =  this.info.getElements().getTypeElement("java.lang.RuntimeException"); // NOI18N
    if (tel != null) {
        runtimeExceptionType = tel.asType();
    } else {
        runtimeExceptionType = null;
    }
    tel =  this.info.getElements().getTypeElement("java.lang.Error"); // NOI18N
    if (tel != null) {
        errorType = tel.asType();
    } else {
        errorType = null;
    }
}
 
Example 4
Source File: Util.java    From GoldenGate with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns the {@link TypeMirror} for a given {@link Class}.
 *
 * Adapter from https://github.com/typetools/checker-framework/
 */
public static TypeMirror typeFromClass(Types types, Elements elements, Class<?> clazz) {
    if (clazz == void.class) {
        return types.getNoType(TypeKind.VOID);
    } else if (clazz.isPrimitive()) {
        String primitiveName = clazz.getName().toUpperCase();
        TypeKind primitiveKind = TypeKind.valueOf(primitiveName);
        return types.getPrimitiveType(primitiveKind);
    } else if (clazz.isArray()) {
        TypeMirror componentType = typeFromClass(types, elements, clazz.getComponentType());
        return types.getArrayType(componentType);
    } else {
        TypeElement element = elements.getTypeElement(clazz.getCanonicalName());
        if (element == null) {
            throw new IllegalArgumentException("Unrecognized class: " + clazz);
        }
        return element.asType();
    }
}
 
Example 5
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static TypeMirror resolveCapturedType(CompilationInfo info, TypeMirror tm) {
    if (tm == null) {
        return tm;
    }
    if (tm.getKind() == TypeKind.ERROR) {
        tm = info.getTrees().getOriginalType((ErrorType) tm);
    }
    TypeMirror type = resolveCapturedTypeInt(info, tm);
    if (type == null) {
        return tm;
    }
    if (type.getKind() == TypeKind.WILDCARD) {
        TypeMirror tmirr = ((WildcardType) type).getExtendsBound();
        if (tmirr != null)
            return tmirr;
        else { //no extends, just '?'
            TypeElement te = info.getElements().getTypeElement("java.lang.Object"); // NOI18N
            return te == null ? null : te.asType();
        }
            
    }
    
    return type;
}
 
Example 6
Source File: ProcessorUtils.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Return the AnnotationMirror for the annotation of the given type on the element provided. */
static AnnotationMirror getAnnotation(
    Elements elementUtils,
    Types typeUtils,
    Element element,
    Class<? extends Annotation> annotation)
    throws OptionProcessorException {
  TypeElement annotationElement = elementUtils.getTypeElement(annotation.getCanonicalName());
  if (annotationElement == null) {
    // This can happen if the annotation is on the -processorpath but not on the -classpath.
    throw new OptionProcessorException(
        element, "Unable to find the type of annotation %s.", annotation);
  }
  TypeMirror annotationMirror = annotationElement.asType();

  for (AnnotationMirror annot : element.getAnnotationMirrors()) {
    if (typeUtils.isSameType(annot.getAnnotationType(), annotationMirror)) {
      return annot;
    }
  }
  // No annotation of this requested type found.
  throw new OptionProcessorException(
      element, "No annotation %s found for this element.", annotation);
}
 
Example 7
Source File: PatternAnalyser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void resolveTypes(Parameters p) {
    
    List<TypeElement> types = ElementFilter.typesIn(p.element.getEnclosedElements());
    
    for (TypeElement typeElement : types) {
        if ( typeElement.getKind() == ElementKind.CLASS ||
             typeElement.getKind() == ElementKind.INTERFACE ) {
            PatternAnalyser pa = new PatternAnalyser( p.ci.getFileObject(), ui );
            pa.analyzeAll(p.ci, typeElement);
            ClassPattern cp = new ClassPattern(pa, typeElement.asType(), 
                                               BeanUtils.nameAsString(typeElement));
            currentClassesPatterns.add(cp);
        }
    }

    
}
 
Example 8
Source File: Flow.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public VisitorImpl(CompilationInfo info, TypeElement undefinedSymbolScope, Cancel cancel) {
    super();
    this.info = info;
    this.cancel = cancel;
    this.undefinedSymbolScope = undefinedSymbolScope;
    this.thisName = info.getElements().getName("this");

    this.throwableEl = info.getElements().getTypeElement("java.lang.Throwable"); // NOI18N
    TypeElement tel =  info.getElements().getTypeElement("java.lang.RuntimeException"); // NOI18N
    if (tel != null) {
        runtimeExceptionType = tel.asType();
    } else {
        runtimeExceptionType = null;
    }
    tel =  info.getElements().getTypeElement("java.lang.Error"); // NOI18N
    if (tel != null) {
        errorType = tel.asType();
    } else {
        errorType = null;
    }
}
 
Example 9
Source File: AddParameterOrLocalFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public AddParameterOrLocalFix(CompilationInfo info,
                              TypeMirror type, String name,
                              ElementKind kind,
                              int /*!!!Position*/ unresolvedVariable) {
    this.file = info.getFileObject();
    if (type.getKind() == TypeKind.NULL || type.getKind() == TypeKind.NONE) {
        TypeElement te = info.getElements().getTypeElement("java.lang.Object"); // NOI18N
        if (te != null) {
            type = te.asType();
            this.type = TypeMirrorHandle.create(type);
        } else {
            this.type = null;
        }
    } else {
        this.type = TypeMirrorHandle.create(type);
    }
    this.name = name;
    this.kind = kind;

    TreePath treePath = info.getTreeUtilities().pathFor(unresolvedVariable + 1);
    tpHandle = new TreePathHandle[1];
    tpHandle[0] = TreePathHandle.create(treePath, info);
}
 
Example 10
Source File: JpaControllerUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static TypeMirror getTypeMirror(WorkingCopy wc, TypeInfo type) {
    TreeMaker make = wc.getTreeMaker();
    String rawType = type.getRawType();
    TypeElement rawTypeElement = wc.getElements().getTypeElement(rawType);
    if (rawTypeElement == null) {
        throw new IllegalArgumentException("Type " + rawType + " cannot be found"); // NOI18N
    }
    TypeInfo[] declaredTypeParameters = type.getDeclaredTypeParameters();
    if (declaredTypeParameters == null || declaredTypeParameters.length == 0) {
        make.QualIdent(rawTypeElement);
        return rawTypeElement.asType();
    }
    else {
        TypeMirror[] declaredTypeMirrors = new TypeMirror[declaredTypeParameters.length];
        for (int i = 0; i < declaredTypeParameters.length; i++) {
            declaredTypeMirrors[i] = getTypeMirror(wc, declaredTypeParameters[i]);
        }
        DeclaredType declaredType = wc.getTypes().getDeclaredType(rawTypeElement, declaredTypeMirrors);
        return declaredType;
    }
}
 
Example 11
Source File: BundleBindingProcessor.java    From pocketknife with Apache License 2.0 5 votes vote down vote up
private BundleBindingAdapterGenerator getOrCreateTargetClass(Map<TypeElement, BundleBindingAdapterGenerator> targetClassMap,
                                                               TypeElement enclosingElement) {
    BundleBindingAdapterGenerator bundleBindingAdapterGenerator = targetClassMap.get(enclosingElement);
    if (bundleBindingAdapterGenerator == null) {
        TypeMirror targetType = enclosingElement.asType();
        String classPackage = getPackageName(enclosingElement);
        String className = getClassName(enclosingElement, classPackage) + BUNDLE_ADAPTER_SUFFIX;

        bundleBindingAdapterGenerator = new BundleBindingAdapterGenerator(classPackage, className, targetType, typeUtil);
        targetClassMap.put(enclosingElement, bundleBindingAdapterGenerator);
    }
    return bundleBindingAdapterGenerator;
}
 
Example 12
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param info context {@link CompilationInfo}
 * @param iterable tested {@link TreePath}
 * @return generic type of an {@link Iterable} or {@link ArrayType} at a TreePath
 */
public static TypeMirror getIterableGenericType(CompilationInfo info, TreePath iterable) {
    TypeElement iterableElement = info.getElements().getTypeElement("java.lang.Iterable"); //NOI18N
    if (iterableElement == null) {
        return null;
    }
    TypeMirror iterableType = info.getTrees().getTypeMirror(iterable);
    if (iterableType == null) {
        return null;
    }
    TypeMirror designedType = null;
    if (iterableType.getKind() == TypeKind.DECLARED) {
        DeclaredType declaredType = (DeclaredType) iterableType;
        if (!info.getTypes().isSubtype(info.getTypes().erasure(declaredType), info.getTypes().erasure(iterableElement.asType()))) {
            return null;
        }
        ExecutableElement iteratorMethod = (ExecutableElement) iterableElement.getEnclosedElements().get(0);
        ExecutableType iteratorMethodType = (ExecutableType) info.getTypes().asMemberOf(declaredType, iteratorMethod);
        List<? extends TypeMirror> typeArguments = ((DeclaredType) iteratorMethodType.getReturnType()).getTypeArguments();
        if (!typeArguments.isEmpty()) {
            designedType = typeArguments.get(0);
        } else {
            TypeElement jlObject = info.getElements().getTypeElement("java.lang.Object");

            if (jlObject != null) {
                designedType = jlObject.asType();
            }
        }
    } else if (iterableType.getKind() == TypeKind.ARRAY) {
        designedType = ((ArrayType) iterableType).getComponentType();
    }
    if (designedType == null) {
        return null;
    }
    return JavaPluginUtils.resolveCapturedType(info, designedType);
}
 
Example 13
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static DeclaredType findDeclaredType(CharSequence fqn, Elements elements) {
    TypeElement re = elements.getTypeElement(fqn);
    if (re != null) {
        TypeMirror asType = re.asType();
        if (asType.getKind() == TypeKind.DECLARED) {
            return (DeclaredType) asType;
        }
    }
    return null;
}
 
Example 14
Source File: CtTypes.java    From doma with Apache License 2.0 5 votes vote down vote up
private TypeMirror reloadTypeMirror(TypeMirror typeMirror) {
  TypeElement typeElement = ctx.getMoreTypes().toTypeElement(typeMirror);
  if (typeElement == null) {
    return null;
  }
  typeElement = ctx.getMoreElements().getTypeElement(typeElement.getQualifiedName());
  if (typeElement == null) {
    return null;
  }
  return typeElement.asType();
}
 
Example 15
Source File: TypeUtils.java    From Mixin with MIT License 5 votes vote down vote up
private static TypeMirror toRawType(ProcessingEnvironment processingEnv, DeclaredType targetType) {
    if (targetType.getKind() == TypeKind.INTERSECTION) {
        return targetType;
    }
    Name qualifiedName = ((TypeElement)targetType.asElement()).getQualifiedName();
    TypeElement typeElement = processingEnv.getElementUtils().getTypeElement(qualifiedName);
    return typeElement != null ? typeElement.asType() : targetType;
}
 
Example 16
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param info context {@link CompilationInfo}
 * @param iterable tested {@link TreePath}
 * @return generic type of an {@link Iterable} or {@link ArrayType} at a TreePath
 */
public static TypeMirror getIterableGenericType(CompilationInfo info, TreePath iterable) {
    TypeElement iterableElement = info.getElements().getTypeElement("java.lang.Iterable"); //NOI18N
    if (iterableElement == null) {
        return null;
    }
    TypeMirror iterableType = info.getTrees().getTypeMirror(iterable);
    if (iterableType == null) {
        return null;
    }
    TypeMirror designedType = null;
    if (iterableType.getKind() == TypeKind.DECLARED) {
        DeclaredType declaredType = (DeclaredType) iterableType;
        if (!info.getTypes().isSubtype(info.getTypes().erasure(declaredType), info.getTypes().erasure(iterableElement.asType()))) {
            return null;
        }
        ExecutableElement iteratorMethod = (ExecutableElement) iterableElement.getEnclosedElements().get(0);
        ExecutableType iteratorMethodType = (ExecutableType) info.getTypes().asMemberOf(declaredType, iteratorMethod);
        List<? extends TypeMirror> typeArguments = ((DeclaredType) iteratorMethodType.getReturnType()).getTypeArguments();
        if (!typeArguments.isEmpty()) {
            designedType = typeArguments.get(0);
        } else {
            TypeElement jlObject = info.getElements().getTypeElement("java.lang.Object");

            if (jlObject != null) {
                designedType = jlObject.asType();
            }
        }
    } else if (iterableType.getKind() == TypeKind.ARRAY) {
        designedType = ((ArrayType) iterableType).getComponentType();
    }
    if (designedType == null) {
        return null;
    }
    return resolveTypeForDeclaration(info, designedType);
}
 
Example 17
Source File: ControllerGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the controller with the component.
 * If a field with the 'id' name does not exist, it creates the field as private,
 * annotated with @FXML. 
 * @param decl 
 */
private void syncComponentBinding(FxInstance decl) {
    String id = decl.getId();
    TypeElement declType = getInstanceType(decl);
    TypeMirror fieldType = generatedFields.get(id);
    if (fieldType != null) {
        return;
    }
    
    VariableTree vt = fields.get(id);
    if (vt == null) {
        if (declType == null) {
            return;
        }
        defineNewField(id, wcopy.getTreeMaker().Type(
                eraseFieldTypeParameters(declType.asType(), wcopy)));
        generatedFields.put(id, declType.asType());
        return;
    }

    // field exists, check its type first
    TreePath varPath = new TreePath(getControllerPath(), vt);
    VariableElement e = (VariableElement) wcopy.getTrees().getElement(varPath);
    if (e == null) {
        throw new IllegalStateException();
    }
    if (declType != null) {
        if (!wcopy.getTypes().isAssignable(
                wcopy.getTypes().erasure(declType.asType()), 
                wcopy.getTypes().erasure(e.asType()))) {
            // the field's type does not match. Consistency of FXML vs. controller is necessary, so 
            // we change field's type even though it may produce a compiler error.
            wcopy.rewrite(vt.getType(), wcopy.getTreeMaker().Type(
                    eraseFieldTypeParameters(declType.asType(), wcopy)));
        }
    }
    // annotation and visibility. If not public, add @FXML annotation
    if (!FxClassUtils.isFxmlAccessible(e)) {
        wcopy.rewrite(vt.getModifiers(), wcopy.getTreeMaker().addModifiersAnnotation(
                vt.getModifiers(), fxmlAnnotationTree));
    }
    mappedTrees.add(vt);
    // prevent further changes to the field
    TypeMirror v;
    if (declType != null) {
        v = declType.asType();
    } else {
        v = e.asType();
    }
    generatedFields.put(id, v);
}
 
Example 18
Source File: RetroWeiboProcessor.java    From SimpleWeibo with Apache License 2.0 4 votes vote down vote up
private void defineVarsForType(TypeElement type, RetroWeiboTemplateVars vars) {
  Types typeUtils = processingEnv.getTypeUtils();
  List<ExecutableElement> methods = new ArrayList<ExecutableElement>();
  findLocalAndInheritedMethods(type, methods);
  determineObjectMethodsToGenerate(methods, vars);
  ImmutableSet<ExecutableElement> methodsToImplement = methodsToImplement(methods);
  Set<TypeMirror> types = new TypeMirrorSet();
  types.addAll(returnTypesOf(methodsToImplement));
  //    TypeMirror javaxAnnotationGenerated = getTypeMirror(Generated.class);
  //    types.add(javaxAnnotationGenerated);
  TypeMirror javaUtilArrays = getTypeMirror(Arrays.class);
  if (containsArrayType(types)) {
    // If there are array properties then we will be referencing java.util.Arrays.
    // Arrange to import it unless that would introduce ambiguity.
    types.add(javaUtilArrays);
  }
  BuilderSpec builderSpec = new BuilderSpec(type, processingEnv, errorReporter);
  Optional<BuilderSpec.Builder> builder = builderSpec.getBuilder();
  ImmutableSet<ExecutableElement> toBuilderMethods;
  if (builder.isPresent()) {
    types.add(getTypeMirror(BitSet.class));
    toBuilderMethods = builder.get().toBuilderMethods(typeUtils, methodsToImplement);
  } else {
    toBuilderMethods = ImmutableSet.of();
  }
  vars.toBuilderMethods =
      FluentIterable.from(toBuilderMethods).transform(SimpleNameFunction.INSTANCE).toList();
  Set<ExecutableElement> propertyMethods = Sets.difference(methodsToImplement, toBuilderMethods);
  String pkg = TypeSimplifier.packageNameOf(type);
  TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtils, pkg, types, type.asType());
  vars.imports = typeSimplifier.typesToImport();
  //    vars.generated = typeSimplifier.simplify(javaxAnnotationGenerated);
  vars.arrays = typeSimplifier.simplify(javaUtilArrays);
  vars.bitSet = typeSimplifier.simplifyRaw(getTypeMirror(BitSet.class));
  ImmutableMap<ExecutableElement, String> methodToPropertyName =
      methodToPropertyNameMap(propertyMethods);
  Map<ExecutableElement, String> methodToIdentifier =
      Maps.newLinkedHashMap(methodToPropertyName);
  fixReservedIdentifiers(methodToIdentifier);
  List<Property> props = new ArrayList<Property>();
  for (ExecutableElement method : propertyMethods) {
    String propertyType = typeSimplifier.simplify(method.getReturnType());
    String propertyName = methodToPropertyName.get(method);
    String identifier = methodToIdentifier.get(method);
    List<String> args = new ArrayList<String>();
    props.add(new Property(propertyName, identifier, method, propertyType, typeSimplifier, processingEnv));
  }
  // If we are running from Eclipse, undo the work of its compiler which sorts methods.
  eclipseHack().reorderProperties(props);
  vars.props = props;
  vars.serialVersionUID = getSerialVersionUID(type);
  vars.formalTypes = typeSimplifier.formalTypeParametersString(type);
  vars.actualTypes = TypeSimplifier.actualTypeParametersString(type);
  vars.wildcardTypes = wildcardTypeParametersString(type);

  TypeElement parcelable = processingEnv.getElementUtils().getTypeElement("android.os.Parcelable");
  vars.parcelable = parcelable != null
      && processingEnv.getTypeUtils().isAssignable(type.asType(), parcelable.asType());
  // Check for @RetroWeibo.Builder and add appropriate variables if it is present.
  if (builder.isPresent()) {
    builder.get().defineVars(vars, typeSimplifier, methodToPropertyName);
  }
}
 
Example 19
Source File: SPGPreferenceParser.java    From SharedPreferencesGenerator with Apache License 2.0 4 votes vote down vote up
private SerializerHolder parseSerializerTypeMirror(Element element, TypeMirror typeMirror) {

        final String s = typeMirror.toString();
        if (VOID.equals(s)) {
            return null;
        }

        final TypeMirror spgInterface = extractSPGSerializerInterface(typeMirror);

        if (spgInterface == null) {
            log(Diagnostic.Kind.ERROR, "Serializer `%s` does not implement SPGSerializer", typeMirror);
            return null;
        }

        final Matcher matcher = SERIALIZER_TYPES.matcher(spgInterface.toString());
        if (!matcher.matches()) {
            log(Diagnostic.Kind.ERROR, "Internal error, could not parse types of: %s", spgInterface);
            return null;
        }

        final String type = matcher.group(1);
        final String repr = matcher.group(2);

        // check against declared type
        // check against representation type
        final TypeElement reprTypeElement = mElements.getTypeElement(repr);
        if (reprTypeElement == null) {
            // could not obtain representation Type. Assume that it's a generic value,
            // we cannot process this
            log(Diagnostic.Kind.ERROR, "Serializer `%s` contains representation type parameter " +
                    "as a generic. Type: %s, interface: %s", typeMirror, spgInterface);
            return null;
        }

        final TypeMirror reprMirror = reprTypeElement.asType();
        final ru.noties.spg.processor.data.KeyType reprKeyType = ru.noties.spg.processor.data.KeyType.parse(reprMirror);
        if (reprKeyType == null) {
            log(Diagnostic.Kind.ERROR, "Representation type for StormSerializer is not supported: %s", reprMirror);
            return null;
        }

        final TypeElement serializerType = mElements.getTypeElement(type);
        if (serializerType == null) {
            // well, assume that it's a generic
            // we cannot check now for it's value
        } else {
            final TypeMirror serializerTypeMirror = serializerType.asType();
            if (!serializerTypeMirror.equals(element.asType())) {
                log(Diagnostic.Kind.ERROR, "Type for StormSerializer is wrong: %s, should be: %s", serializerTypeMirror, element.asType());
                return null;
            }
        }

        return new SerializerHolder(s, reprKeyType);
    }
 
Example 20
Source File: GeneratedTypeElement.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public static GeneratedTypeElement newIosType(
    String name, ElementKind kind, TypeElement superclass, String header) {
  return new GeneratedTypeElement(
      name, kind, null, superclass != null ? superclass.asType() : null, NestingKind.TOP_LEVEL,
      header, true, false);
}