javax.lang.model.element.TypeElement#asType ( )源码实例Demo

下面列出了javax.lang.model.element.TypeElement#asType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: netbeans   文件: JpaControllerUtil.java
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;
    }
}
 
源代码2 项目: j2objc   文件: GraphBuilder.java
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);
  }
}
 
源代码3 项目: netbeans   文件: AddParameterOrLocalFix.java
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);
}
 
源代码4 项目: netbeans   文件: Flow.java
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;
    }
}
 
源代码5 项目: netbeans   文件: PatternAnalyser.java
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);
        }
    }

    
}
 
源代码6 项目: bazel   文件: ProcessorUtils.java
/** 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);
}
 
源代码7 项目: netbeans   文件: Utilities.java
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;
}
 
源代码8 项目: GoldenGate   文件: Util.java
/**
 * 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();
    }
}
 
源代码9 项目: netbeans   文件: NPECheck.java
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;
    }
}
 
源代码10 项目: netbeans   文件: CreateEnumConstant.java
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);
    }
}
 
源代码11 项目: doma   文件: CtTypes.java
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();
}
 
源代码12 项目: netbeans   文件: JavadocCompletionQuery.java
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;
}
 
源代码13 项目: pocketknife   文件: BundleBindingProcessor.java
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;
}
 
源代码14 项目: netbeans   文件: CreateElementUtilities.java
/**
 *
 * @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);
}
 
源代码15 项目: Mixin   文件: TypeUtils.java
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;
}
 
源代码16 项目: netbeans   文件: Utilities.java
/**
 *
 * @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);
}
 
源代码17 项目: j2objc   文件: GeneratedTypeElement.java
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);
}
 
源代码18 项目: netbeans   文件: ControllerGenerator.java
/**
 * 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);
}
 
源代码19 项目: SimpleWeibo   文件: RetroWeiboProcessor.java
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);
  }
}
 
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);
    }