javax.lang.model.util.Types类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(16.2k)|赞(0)|评价(0)|浏览(156)

本文整理了Java中javax.lang.model.util.Types类的一些代码示例,展示了Types类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Types类的具体详情如下:
包路径:javax.lang.model.util.Types
类名称:Types

Types介绍

[英]Utility methods for operating on types.

Compatibility Note: Methods may be added to this interface in future releases of the platform.
[中]对类型进行操作的实用方法。
兼容性说明:在平台的未来版本中,可能会向该接口添加方法。

代码示例

代码示例来源:origin: airbnb/epoxy

/**
 * Check if the given class or any of its super classes have a super method with the given name.
 * Private methods are ignored since the generated subclass can't call super on those.
 */
protected boolean hasSuperMethod(TypeElement classElement, Element attribute) {
 if (!Utils.isEpoxyModel(classElement.asType())) {
  return false;
 }
 for (Element subElement : classElement.getEnclosedElements()) {
  if (subElement.getKind() == ElementKind.METHOD) {
   ExecutableElement method = (ExecutableElement) subElement;
   if (!method.getModifiers().contains(Modifier.PRIVATE)
     && method.getSimpleName().toString().equals(attribute.getSimpleName().toString())
     && method.getParameters().size() == 1
     && method.getParameters().get(0).asType().equals(attribute.asType())) {
    return true;
   }
  }
 }
 Element superClass = typeUtils.asElement(classElement.getSuperclass());
 return (superClass instanceof TypeElement)
   && hasSuperMethod((TypeElement) superClass, attribute);
}

代码示例来源:origin: chenenyu/Router

private boolean validateElement(Element element) {
  return element.getKind().isClass() && processingEnv.getTypeUtils().isAssignable(element.asType(),
      processingEnv.getElementUtils().getTypeElement(INTERCEPTOR_FULL_NAME).asType());
}

代码示例来源:origin: neo4j/neo4j

private Stream<CompilationMessage> validateReturnType( ExecutableElement method )
{
  String streamClassName = Stream.class.getCanonicalName();
  TypeMirror streamType = typeUtils.erasure( elementUtils.getTypeElement( streamClassName ).asType() );
  TypeMirror returnType = method.getReturnType();
  TypeMirror erasedReturnType = typeUtils.erasure( returnType );
  TypeMirror voidType = typeUtils.getNoType( TypeKind.VOID );
  if ( typeUtils.isSameType( returnType, voidType ) )
  {
    return Stream.empty();
  }
  if ( !typeUtils.isSubtype( erasedReturnType, streamType ) )
  {
    return Stream.of( new ReturnTypeError( method, "Return type of %s#%s must be %s",
        method.getEnclosingElement().getSimpleName(), method.getSimpleName(), streamClassName ) );
  }
  return recordVisitor.visit( returnType );
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Return the super class of the specified {@link Element} or null if this
 * {@code element} represents {@link Object}.
 */
public Element getSuperClass(Element element) {
  List<? extends TypeMirror> superTypes = this.types.directSupertypes(element.asType());
  if (superTypes.isEmpty()) {
    return null;  // reached java.lang.Object
  }
  return this.types.asElement(superTypes.get(0));
}

代码示例来源:origin: airbnb/epoxy

static boolean isSubtype(TypeMirror e1, TypeMirror e2, Types types) {
 return types.isSubtype(e1, types.erasure(e2));
}

代码示例来源:origin: neo4j/neo4j

private boolean isSameErasedType( Class<?> type, TypeMirror typeMirror )
{
  return typeUtils
      .isSameType( typeUtils.erasure( typeMirrors.typeMirror( type ) ), typeUtils.erasure( typeMirror ) );
}

代码示例来源:origin: square/dagger

Elements elementUtils = processingEnv.getElementUtils();
Types types = processingEnv.getTypeUtils();
 switch (providerMethod.getEnclosingElement().getKind()) {
  case CLASS:
   break; // valid, move along
   continue;
 if (!providerMethodAsExecutable.getThrownTypes().isEmpty()) {
  error("@Provides methods must not have a throws clause: "
    + type.getQualifiedName() + "." + providerMethod, providerMethod);
 TypeMirror returnType = types.erasure(providerMethodAsExecutable.getReturnType());
 if (!returnType.getKind().equals(TypeKind.ERROR)) {
   TypeElement invalidTypeElement = elementUtils.getTypeElement(invalidTypeName);
   if (invalidTypeElement != null && types.isSameType(returnType,
     types.erasure(invalidTypeElement.asType()))) {
    error(String.format("@Provides method must not return %s directly: %s.%s",
      invalidTypeElement, type.getQualifiedName(), providerMethod), providerMethod);
TypeMirror objectType = elementUtils.getTypeElement("java.lang.Object").asType();
 if (!types.isSameType(moduleType.getSuperclass(), objectType)) {
  error("Modules must not extend from other classes: " + elementToString(module), module);

代码示例来源:origin: org.netbeans.api/org-openide-util-lookup

@Override
public Iterable<? extends Completion> getCompletions(Element annotated, AnnotationMirror annotation, ExecutableElement attr, String userText) {
  if (processingEnv == null || annotated == null || !annotated.getKind().isClass()) {
    return Collections.emptyList();
    || !"org.openide.util.lookup.ServiceProvider".contentEquals(((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName())) {
    return Collections.emptyList();
  if (!"service".contentEquals(attr.getSimpleName())) {
    return Collections.emptyList();
  TypeElement jlObject = processingEnv.getElementUtils().getTypeElement("java.lang.Object");
    TypeElement c = toProcess.remove(0);
    result.add(new TypeCompletion(c.getQualifiedName().toString() + ".class"));
    parents.add(c.getSuperclass());
    parents.addAll(c.getInterfaces());
      if (tm == null || tm.getKind() != TypeKind.DECLARED) {
        continue;
      TypeElement type = (TypeElement) processingEnv.getTypeUtils().asElement(tm);

代码示例来源:origin: airbnb/epoxy

/**
 * Get information about methods returning class type of the original class so we can duplicate
 * them in the generated class for chaining purposes
 */
protected void collectMethodsReturningClassType(TypeElement modelClass, Types typeUtils) {
 TypeElement clazz = modelClass;
 while (clazz.getSuperclass().getKind() != TypeKind.NONE) {
  for (Element subElement : clazz.getEnclosedElements()) {
   Set<Modifier> modifiers = subElement.getModifiers();
   if (subElement.getKind() == ElementKind.METHOD
     && !modifiers.contains(Modifier.PRIVATE)
     && !modifiers.contains(Modifier.FINAL)
     && !modifiers.contains(Modifier.STATIC)) {
    TypeMirror methodReturnType = ((ExecutableType) subElement.asType()).getReturnType();
    if (methodReturnType.equals(clazz.asType())
      || typeUtils.isSubtype(clazz.asType(), methodReturnType)) {
     ExecutableElement castedSubElement = ((ExecutableElement) subElement);
     List<? extends VariableElement> params = castedSubElement.getParameters();
     String methodName = subElement.getSimpleName().toString();
     if (methodName.equals(RESET_METHOD) && params.isEmpty()) {
      continue;
     }
     methodsReturningClassType.add(new MethodInfo(methodName, modifiers,
       buildParamSpecs(params), castedSubElement.isVarArgs()));
    }
   }
  }
  clazz = (TypeElement) typeUtils.asElement(clazz.getSuperclass());
 }
}

代码示例来源:origin: org.netbeans.api/org-openide-util-lookup

continue;
  final TypeMirror toCheck = attr.getReturnType();
  TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType(); // NOI18N
  if (processingEnv.getTypeUtils().isAssignable(toCheck, stringType)) {
    continue;
  ArrayType arrStringType = processingEnv.getTypeUtils().getArrayType(stringType);
  if (processingEnv.getTypeUtils().isAssignable(toCheck, arrStringType)) {
    continue;
    if (!processingEnv.getTypeUtils().isSameType(
      processingEnv.getTypeUtils().getPrimitiveType(TypeKind.INT),
      attr.getReturnType()
Retention ret = e.getAnnotation(Retention.class);
Target tar = e.getAnnotation(Target.class);
  int cnt = 0;
  for (Class<?> type : nsd.serviceType()) {
    TypeMirror typeMirror = processingEnv.getTypeUtils().erasure(asType(type));
    if (processingEnv.getTypeUtils().isSubtype(e.asType(), typeMirror)) {
      cnt++;
      for (String p : findPath(nsd.path(), a)) {

代码示例来源:origin: greenrobot/EventBus

private void writeCreateSubscriberMethods(BufferedWriter writer, List<ExecutableElement> methods,
                     String callPrefix, String myPackage) throws IOException {
  for (ExecutableElement method : methods) {
    List<? extends VariableElement> parameters = method.getParameters();
    TypeMirror paramType = getParamTypeMirror(parameters.get(0), null);
    TypeElement paramElement = (TypeElement) processingEnv.getTypeUtils().asElement(paramType);
    String methodName = method.getSimpleName().toString();
    String eventClass = getClassString(paramElement, myPackage) + ".class";
    Subscribe subscribe = method.getAnnotation(Subscribe.class);
    List<String> parts = new ArrayList<>();
    parts.add(callPrefix + "(\"" + methodName + "\",");
      processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Indexed @Subscribe at " +
          method.getEnclosingElement().getSimpleName() + "." + methodName +
          "(" + paramElement.getSimpleName() + ")");

代码示例来源:origin: chenenyu/Router

private boolean isSubtype(Element typeElement, String type) {
  return processingEnv.getTypeUtils().isSubtype(typeElement.asType(),
      processingEnv.getElementUtils().getTypeElement(type).asType());
}

代码示例来源:origin: androidannotations/androidannotations

public void validateInterceptors(Element element, ElementValidation valid) {
  TypeMirror clientHttpRequestInterceptorType = annotationHelper.typeElementFromQualifiedName(CLIENT_HTTP_REQUEST_INTERCEPTOR).asType();
  TypeMirror clientHttpRequestInterceptorTypeErased = annotationHelper.getTypeUtils().erasure(clientHttpRequestInterceptorType);
  List<DeclaredType> interceptors = annotationHelper.extractAnnotationClassArrayParameter(element, annotationHelper.getTarget(), "interceptors");
  if (interceptors == null) {
    TypeMirror erasedInterceptorType = annotationHelper.getTypeUtils().erasure(interceptorType);
    if (annotationHelper.isSubtype(erasedInterceptorType, clientHttpRequestInterceptorTypeErased)) {
      Element interceptorElement = interceptorType.asElement();
      if (interceptorElement.getKind().isClass()) {
        if (!annotationHelper.isAbstract(interceptorElement)) {
          if (interceptorElement.getAnnotation(EBean.class) == null) {
            List<ExecutableElement> constructors = ElementFilter.constructorsIn(interceptorElement.getEnclosedElements());
            boolean hasPublicWithNoArgumentConstructor = false;
            for (ExecutableElement constructor : constructors) {
              if (annotationHelper.isPublic(constructor) && constructor.getParameters().isEmpty()) {
                hasPublicWithNoArgumentConstructor = true;

代码示例来源:origin: bluelinelabs/LoganSquare

private boolean ensureTypeConverterClassValid(TypeMirror typeConverterClassMirror, Elements elements, Types types) {
  TypeElement typeConverterElement = elements.getTypeElement(typeConverterClassMirror.toString());
      for (TypeMirror iface : element.getInterfaces()) {
        if (types.erasure(iface).toString().equals(TypeConverter.class.getCanonicalName())) {
          isTypeConverterType = true;
      TypeMirror superClassMirror = element.getSuperclass();
      if (superClassMirror != null) {
        superClassMirror = types.erasure(superClassMirror);
        element = elements.getTypeElement(superClassMirror.toString());
      } else {
        element = null;
    List<? extends Element> enclosedElements = typeConverterElement.getEnclosedElements();
    for (Element enclosedElement : enclosedElements) {
      ElementKind enclosedElementKind = enclosedElement.getKind();
      if (enclosedElementKind == ElementKind.CONSTRUCTOR) {
        constructorIsDeclared = true;
        if (!enclosedElement.getModifiers().contains(Modifier.PRIVATE)) {
          ExecutableElement executableElement = (ExecutableElement)enclosedElement;
          if (executableElement.getParameters().size() == 0) {
            hasAccessibleConstructor = true;

代码示例来源:origin: immutables/immutables

/**
 * Returns true if there's a public way to build the value type with an instance no-arg method.
 *
 * @param attribute value attribute to check.
 * @param possibleBuildMethod method which matches {@link StyleMirror#attributeBuilder()}
 * @return true if this is the possibleBuildMethod can build the value type.
 */
private static boolean isPossibleBuildMethod(ValueAttribute attribute, Element possibleBuildMethod) {
 if (possibleBuildMethod.getKind() != ElementKind.METHOD) {
  return false;
 }
 if (!attribute.containingType.names().possibleAttributeBuilder(possibleBuildMethod.getSimpleName())) {
  return false;
 }
 Types typeUtils = attribute.containingType.constitution.protoclass()
   .environment()
   .processing()
   .getTypeUtils();
 ExecutableElement candidateBuildMethod = (ExecutableElement) possibleBuildMethod;
 return !candidateBuildMethod.getModifiers().contains(Modifier.STATIC)
   && candidateBuildMethod.getModifiers().contains(Modifier.PUBLIC)
   && candidateBuildMethod.getTypeParameters().isEmpty()
   && candidateBuildMethod.getReturnType().getKind() == TypeKind.DECLARED
   && typeUtils.isSameType(candidateBuildMethod.getReturnType(), attribute.containedTypeElement.asType());
}

代码示例来源:origin: querydsl/querydsl

private Type createClassType(DeclaredType declaredType, TypeElement typeElement, boolean deep) {
  String name = typeElement.getQualifiedName().toString();
    Iterator<? extends TypeMirror> i = declaredType.getTypeArguments().iterator();
      && isAssignable(typeElement.asType(), comparableType)
      && isSubType(typeElement.asType(), numberType)) {
    typeCategory = TypeCategory.NUMERIC;
  List<? extends TypeMirror> arguments = declaredType.getTypeArguments();
    List<? extends TypeMirror> superTypes = env.getTypeUtils().directSupertypes(declaredType);
    for (TypeMirror superType : superTypes) {
      if (env.getTypeUtils().isSubtype(superType, type)) {
        type = superType;
    typeElement = (TypeElement) env.getTypeUtils().asElement(type);
    if (type instanceof DeclaredType) {
      arguments = ((DeclaredType) type).getTypeArguments();

代码示例来源:origin: immutables/immutables

private Set<String> useProvidedTypesForServices(TypeElement typeElement, ImmutableList<TypeMirror> typesMirrors) {
 List<String> wrongTypes = Lists.newArrayList();
 List<String> types = Lists.newArrayList();
 for (TypeMirror typeMirror : typesMirrors) {
  if (typeMirror.getKind() != TypeKind.DECLARED
    || !processing().getTypeUtils().isAssignable(typeElement.asType(), typeMirror)) {
   wrongTypes.add(typeMirror.toString());
  } else {
   types.add(typeMirror.toString());
  }
 }
 if (!wrongTypes.isEmpty()) {
  processing().getMessager().printMessage(
    Diagnostic.Kind.ERROR,
    "@Metainf.Service(value = {...}) contains types that are not implemented by "
      + typeElement.getSimpleName()
      + ": " + wrongTypes,
    typeElement,
    AnnotationMirrors.findAnnotation(typeElement.getAnnotationMirrors(), Metainf.Service.class));
 }
 return FluentIterable.from(types).toSet();
}

代码示例来源:origin: pf4j/pf4j

for (AnnotationValue extensionPointClass : extensionPointClasses) {
  String extensionPointClassName = extensionPointClass.getValue().toString();
  TypeElement extensionPointElement = processingEnv.getElementUtils().getTypeElement(extensionPointClassName);
  extensionPointElements.add(extensionPointElement);
for (TypeMirror item : extensionElement.getInterfaces()) {
  boolean isExtensionPoint = processingEnv.getTypeUtils().isSubtype(item, getExtensionPointType());
  if (isExtensionPoint) {
    TypeElement extensionPointElement = (TypeElement) ((DeclaredType) item).asElement();
    extensionPointElements.add(extensionPointElement);
TypeMirror superclass = extensionElement.getSuperclass();
if (superclass.getKind() != TypeKind.NONE) {
  boolean isExtensionPoint = processingEnv.getTypeUtils().isSubtype(superclass, getExtensionPointType());
  if (isExtensionPoint) {
    TypeElement extensionPointElement = (TypeElement) ((DeclaredType) superclass).asElement();
    extensionPointElements.add(extensionPointElement);

代码示例来源:origin: sockeqwe/fragmentargs

private TypeMirror getWildcardType(String type, String elementType) {
  TypeElement arrayList = processingEnv.getElementUtils().getTypeElement(type);
  TypeMirror elType = processingEnv.getElementUtils().getTypeElement(elementType).asType();
  return processingEnv.getTypeUtils()
      .getDeclaredType(arrayList, processingEnv.getTypeUtils().getWildcardType(elType, null));
}

代码示例来源:origin: androidannotations/androidannotations

public JInvocation getSuperPutExtraInvocation(TypeMirror elementType, JVar extraParam, JFieldVar extraKeyField) {
  IJExpression extraParameterArg = extraParam;
  // Cast to Parcelable, wrap with Parcels.wrap or cast Serializable if needed
  if (elementType.getKind() == TypeKind.DECLARED) {
    Elements elementUtils = environment.getProcessingEnvironment().getElementUtils();
    TypeMirror parcelableType = elementUtils.getTypeElement(PARCELABLE).asType();
    if (typeUtils.isSubtype(elementType, parcelableType)) {
      TypeMirror serializableType = elementUtils.getTypeElement(SERIALIZABLE).asType();
      if (typeUtils.isSubtype(elementType, serializableType)) {
        extraParameterArg = cast(environment.getClasses().PARCELABLE, extraParameterArg);
      }
    } else if (!BundleHelper.METHOD_SUFFIX_BY_TYPE_NAME.containsKey(elementType.toString()) && parcelerHelper.isParcelType(elementType)) {
      extraParameterArg = environment.getJClass(CanonicalNameConstants.PARCELS_UTILITY_CLASS).staticInvoke("wrap").arg(extraParameterArg);
    } else {
      TypeMirror stringType = elementUtils.getTypeElement(STRING).asType();
      if (!typeUtils.isSubtype(elementType, stringType)) {
        extraParameterArg = cast(environment.getClasses().SERIALIZABLE, extraParameterArg);
      }
    }
  }
  return _super().invoke("extra").arg(extraKeyField).arg(extraParameterArg);
}

相关文章