Java Code Examples for javax.lang.model.util.Types#isSubtype()

The following examples show how to use javax.lang.model.util.Types#isSubtype() . 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: WebServiceVisitor.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
protected boolean sameMethod(ExecutableElement method1, ExecutableElement method2) {
    if (!method1.getSimpleName().equals(method2.getSimpleName()))
        return false;
    Types typeUtils = builder.getProcessingEnvironment().getTypeUtils();
    if(!typeUtils.isSameType(method1.getReturnType(), method2.getReturnType())
            && !typeUtils.isSubtype(method2.getReturnType(), method1.getReturnType()))
        return false;
    List<? extends VariableElement> parameters1 = method1.getParameters();
    List<? extends VariableElement> parameters2 = method2.getParameters();
    if (parameters1.size() != parameters2.size())
        return false;
    for (int i = 0; i < parameters1.size(); i++) {
        if (!typeUtils.isSameType(parameters1.get(i).asType(), parameters2.get(i).asType()))
            return false;
    }
    return true;
}
 
Example 2
Source File: WebServiceVisitor.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
protected boolean sameMethod(ExecutableElement method1, ExecutableElement method2) {
    if (!method1.getSimpleName().equals(method2.getSimpleName()))
        return false;
    Types typeUtils = builder.getProcessingEnvironment().getTypeUtils();
    if(!typeUtils.isSameType(method1.getReturnType(), method2.getReturnType())
            && !typeUtils.isSubtype(method2.getReturnType(), method1.getReturnType()))
        return false;
    List<? extends VariableElement> parameters1 = method1.getParameters();
    List<? extends VariableElement> parameters2 = method2.getParameters();
    if (parameters1.size() != parameters2.size())
        return false;
    for (int i = 0; i < parameters1.size(); i++) {
        if (!typeUtils.isSameType(parameters1.get(i).asType(), parameters2.get(i).asType()))
            return false;
    }
    return true;
}
 
Example 3
Source File: RetroWeiboProcessor.java    From SimpleWeibo with Apache License 2.0 6 votes vote down vote up
public String buildCallbackType(ExecutableElement method) {
  Types typeUtils = processingEnv.getTypeUtils();
  TypeMirror callback = getTypeMirror(processingEnv, RetroWeibo.Callback.class);

  List<? extends VariableElement> parameters = method.getParameters();
  for (VariableElement parameter : parameters) {
    TypeMirror type = parameter.asType();
    if (type instanceof DeclaredType) {
      List<? extends TypeMirror> params = ((DeclaredType) type).getTypeArguments();
      if (params.size() == 1) {
        callback = typeUtils.getDeclaredType((TypeElement) typeUtils
                .asElement(callback), new TypeMirror[] {params.get(0)});

        if (typeUtils.isSubtype(type, callback)) {
          return typeSimplifier.simplify(params.get(0));
        }
      }
    }
  }
  return "";
}
 
Example 4
Source File: WebServiceVisitor.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
protected boolean sameMethod(ExecutableElement method1, ExecutableElement method2) {
    if (!method1.getSimpleName().equals(method2.getSimpleName()))
        return false;
    Types typeUtils = builder.getProcessingEnvironment().getTypeUtils();
    if(!typeUtils.isSameType(method1.getReturnType(), method2.getReturnType())
            && !typeUtils.isSubtype(method2.getReturnType(), method1.getReturnType()))
        return false;
    List<? extends VariableElement> parameters1 = method1.getParameters();
    List<? extends VariableElement> parameters2 = method2.getParameters();
    if (parameters1.size() != parameters2.size())
        return false;
    for (int i = 0; i < parameters1.size(); i++) {
        if (!typeUtils.isSameType(parameters1.get(i).asType(), parameters2.get(i).asType()))
            return false;
    }
    return true;
}
 
Example 5
Source File: MetamodelAttribute.java    From spring-data-jpa-entity-graph with MIT License 6 votes vote down vote up
public static Optional<MetamodelAttribute> parse(
    Elements elements, Types types, Element element) {
  if (!(element instanceof VariableElement)) {
    return Optional.empty();
  }

  VariableElement variableElement = (VariableElement) element;
  if (variableElement.getKind() != FIELD) {
    return Optional.empty();
  }

  TypeElement attributeTypeElement = elements.getTypeElement(Attribute.class.getCanonicalName());
  if (!types.isSubtype(
      types.erasure(variableElement.asType()), types.erasure(attributeTypeElement.asType()))) {
    return Optional.empty();
  }

  return Optional.of(new MetamodelAttribute(variableElement));
}
 
Example 6
Source File: PipelineAnnotationsProcessor.java    From datacollector-api with Apache License 2.0 6 votes vote down vote up
private StageType extractStageType(TypeMirror stageType) {
  Types typeUtils = processingEnv.getTypeUtils();
  StageType type;
  if (typeUtils.isAssignable(stageType, typeOfSource) || typeUtils.isAssignable(stageType, typeOfPushSource)) {
    type = StageType.SOURCE;
  } else if (typeUtils.isSubtype(stageType, typeOfProcessor)) {
    type = StageType.PROCESSOR;
  } else if (typeUtils.isSubtype(stageType, typeOfExecutor)) {
    type = StageType.EXECUTOR;
  } else if (typeUtils.isSubtype(stageType, typeOfTarget)) {
    type = StageType.TARGET;
  } else {
    type = null;
  }
  return type;
}
 
Example 7
Source File: WebServiceVisitor.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
protected boolean sameMethod(ExecutableElement method1, ExecutableElement method2) {
    if (!method1.getSimpleName().equals(method2.getSimpleName()))
        return false;
    Types typeUtils = builder.getProcessingEnvironment().getTypeUtils();
    if(!typeUtils.isSameType(method1.getReturnType(), method2.getReturnType())
            && !typeUtils.isSubtype(method2.getReturnType(), method1.getReturnType()))
        return false;
    List<? extends VariableElement> parameters1 = method1.getParameters();
    List<? extends VariableElement> parameters2 = method2.getParameters();
    if (parameters1.size() != parameters2.size())
        return false;
    for (int i = 0; i < parameters1.size(); i++) {
        if (!typeUtils.isSameType(parameters1.get(i).asType(), parameters2.get(i).asType()))
            return false;
    }
    return true;
}
 
Example 8
Source File: AutoServiceProcessor.java    From mica-auto with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Verifies {@link java.util.spi.LocaleServiceProvider} constraints on the concrete provider class.
 * Note that these constraints are enforced at runtime via the ServiceLoader,
 * we're just checking them at compile time to be extra nice to our users.
 */
private boolean checkImplementer(Element providerImplementer, TypeMirror providerType) {
	// TODO: We're currently only enforcing the subtype relationship
	// constraint. It would be nice to enforce them all.
	Types types = processingEnv.getTypeUtils();
	return types.isSubtype(providerImplementer.asType(), providerType);
}
 
Example 9
Source File: SaveStateProcessor.java    From Aurora with Apache License 2.0 5 votes vote down vote up
private boolean checkIsSubClassOf(Element element, String... superClasses) {
    Elements elementUtils = processingEnv.getElementUtils();
    Types typeUtils = processingEnv.getTypeUtils();
    for (String clazz : superClasses) {
        boolean isSubType = typeUtils.isSubtype(
                element.asType(),
                elementUtils.getTypeElement(clazz).asType()
        );
        if (isSubType) return true;
    }
    return false;
}
 
Example 10
Source File: AutoServiceProcessor.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies {@link ServiceProvider} constraints on the concrete provider class.
 * Note that these constraints are enforced at runtime via the ServiceLoader,
 * we're just checking them at compile time to be extra nice to our users.
 */
private boolean checkImplementer(TypeElement providerImplementer, TypeElement providerType) {

  String verify = processingEnv.getOptions().get("verify");
  if (verify == null || !Boolean.valueOf(verify)) {
    return true;
  }

  // TODO: We're currently only enforcing the subtype relationship
  // constraint. It would be nice to enforce them all.

  Types types = processingEnv.getTypeUtils();

  return types.isSubtype(providerImplementer.asType(), providerType.asType());
}
 
Example 11
Source File: ColumnElement.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
public static TypeName findEquivalentType(ExtendedTypeElement serializedType,
                                          Environment environment) {
  final Types typeUtils = environment.getTypeUtils();
  TypeMirror typeMirror = serializedType.getTypeMirror();
  if (typeMirror instanceof PrimitiveType) {
    typeMirror = typeUtils.boxedClass((PrimitiveType) typeMirror).asType();
  }
  if (typeUtils.isSubtype(typeMirror, NUMBER_TYPE)) {
    return NUMBER;
  }
  if (typeUtils.isSubtype(typeMirror, CHAR_SEQUENCE_TYPE)) {
    return CHAR_SEQUENCE;
  }
  return typeNameForGenerics(serializedType);
}
 
Example 12
Source File: BaseTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
TypeMirror asMemberOf(Element element, TypeMirror type, Types types) {
    TypeMirror ret = element.asType();
    TypeMirror enclType = element.getEnclosingElement().asType();
    if (enclType.getKind() == TypeKind.DECLARED) {
        enclType = types.erasure(enclType);
    }
    while (type != null && type.getKind() == TypeKind.DECLARED) {
        if ((enclType.getKind() != TypeKind.DECLARED || ((DeclaredType) enclType).asElement().getSimpleName().length() > 0) && types.isSubtype(type, enclType)) {
            ret = types.asMemberOf((DeclaredType) type, element);
            break;
        }
        type = ((DeclaredType) type).getEnclosingType();
    }
    return ret;
}
 
Example 13
Source File: LookupProviderAnnotationProcessor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<TypeMirror> findServiceAnnotation(Element e) throws LayerGenerationException {
    for (AnnotationMirror ann : e.getAnnotationMirrors()) {
        if (!ProjectServiceProvider.class.getName().equals(ann.getAnnotationType().toString())) {
            continue;
        }
        for (Map.Entry<? extends ExecutableElement,? extends AnnotationValue> attr : ann.getElementValues().entrySet()) {
            if (!attr.getKey().getSimpleName().contentEquals("service")) {
                continue;
            }
            List<TypeMirror> r = new ArrayList<TypeMirror>();
            for (Object item : (List<?>) attr.getValue().getValue()) {
                TypeMirror type = (TypeMirror) ((AnnotationValue) item).getValue();
                Types typeUtils = processingEnv.getTypeUtils();
                for (TypeMirror otherType : r) {
                    for (boolean swap : new boolean[] {false, true}) {
                        TypeMirror t1 = swap ? type : otherType;
                        TypeMirror t2 = swap ? otherType : type;
                        if (typeUtils.isSubtype(t1, t2)) {
                            processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "registering under both " + typeUtils.asElement(t2).getSimpleName() + " and its subtype " + typeUtils.asElement(t1).getSimpleName() + " will not work if LookupMerger<" + typeUtils.asElement(t2).getSimpleName() + "> is used (#205151)", e, ann, attr.getValue());
                        }
                    }
                }
                r.add(type);
            }
            return r;
        }
        throw new LayerGenerationException("No service attr found", e);
    }
    throw new LayerGenerationException("No @ProjectServiceProvider found", e);
}
 
Example 14
Source File: Refactorer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Boolean isRefactorable() {
    prospectives = this.getListRepresentation(loop.getStatement(), true);
    if (prospectives != null && !prospectives.isEmpty()) {
        prospectives.get(prospectives.size() - 1).eagerize();
        if (this.untrasformable) {
            return false;
        }
        for ( int i = 0; i < prospectives.size() - 1; i++) {
            if (!prospectives.get(i).isLazy()) {
                return false;
            }
        }
        hasIterable = false;
        VariableTree var = loop.getVariable();
        TypeElement el = workingCopy.getElements().getTypeElement("java.lang.Iterable"); // NOI18N
        if (el != null) {
            TreePath path = TreePath.getPath(workingCopy.getCompilationUnit(), loop.getExpression());
            TypeMirror m = workingCopy.getTrees().getTypeMirror(path);
            Types types  = workingCopy.getTypes();
            hasIterable = 
                    types.isSubtype(
                        types.erasure(m),
                        types.erasure(el.asType())
                    );
        }
        prospectives = ProspectiveOperation.mergeIntoComposableOperations(prospectives);
        return prospectives != null;

    } else {
        return false;
    }

}
 
Example 15
Source File: ProcessorUtils.java    From MRouter with Apache License 2.0 4 votes vote down vote up
public static boolean isParcelable(Elements elements, Types types, TypeMirror typeMirror) {
    TypeMirror typeParcelable = elements.getTypeElement(Constant.PARCELABLE).asType();
    return types.isSubtype(typeMirror, typeParcelable);
}
 
Example 16
Source File: ExtraAnnotatedClass.java    From PrettyBundle with Apache License 2.0 4 votes vote down vote up
public ExtraAnnotatedClass(VariableElement annotatedVariableElement, Elements elements, Types types) {
    this.annotatedVariableElement = annotatedVariableElement;
    key = annotatedVariableElement.getSimpleName().toString();
    // Get the full QualifiedTypeName
    final TypeElement parent = (TypeElement) annotatedVariableElement.getEnclosingElement();
    if (types.isSubtype(parent.asType(), elements.getTypeElement("android.app.Activity").asType())) {
        supportedType = SupportedType.ACTIVITY;
    } else if (types.isSubtype(parent.asType(), elements.getTypeElement("android.app.Service").asType())) {
        supportedType = SupportedType.SERVICE;
    } else if (types.isSubtype(parent.asType(), elements.getTypeElement("android.app.Fragment").asType())
            || types.isSubtype(parent.asType(), elements.getTypeElement("android.support.v4.app.Fragment").asType())) {
        supportedType = SupportedType.FRAGMENT;
    } else {
        supportedType = SupportedType.NOP;
    }
    qualifiedClassName = parent.getQualifiedName().toString();
    // Get the full Qualified of DataType.
    dataType = annotatedVariableElement.asType();
    dataTypeQualifiedClassName = dataType.toString();
    extraBinder = ExtraBinderProvider.get(dataTypeQualifiedClassName);
    if (extraBinder != ExtraBinder.NOP) {
        return;
    }
    // Check if data type is kind of Parcelable.
    if (types.isSubtype(dataType, elements.getTypeElement("android.os.Parcelable").asType())) {
        extraBinder = ExtraBinderProvider.get("android.os.Parcelable");
        if (extraBinder != ExtraBinder.NOP) {
            return;
        }
    }

    try {
        // Check if data type is kind of Array.
        dataTypeQualifiedClassName = ((ArrayType) dataType).getComponentType().toString();
        final TypeMirror componentTypeMirror = elements.getTypeElement(dataTypeQualifiedClassName).asType();
        if (types.isSubtype(componentTypeMirror, elements.getTypeElement("android.os.Parcelable").asType())) {
            extraBinder = ExtraBinderProvider.get("android.os.Parcelable[]");
            if (extraBinder != ExtraBinder.NOP) {
                return;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 17
Source File: Tiny.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static ErrorDescription enumHint(HintContext ctx, String baseName, String targetTypeName, String key, Fix... fixes) {
    Element type = ctx.getInfo().getTrees().getElement(ctx.getVariables().get("$param"));

    if (type == null || type.getKind() != ElementKind.ENUM) {
        return null;
    }

    Element coll = ctx.getInfo().getTrees().getElement(ctx.getVariables().get("$coll"));

    if (coll == null || coll.getKind() != ElementKind.CLASS) {
        return null;
    }
    
    TypeElement base = ctx.getInfo().getElements().getTypeElement(baseName);
    
    if (base == null) {
        return null;
    }

    Types t = ctx.getInfo().getTypes();

    if (!t.isSubtype(t.erasure(coll.asType()), t.erasure(base.asType()))) {
        return null;
    }

    if (targetTypeName != null) {
        TypeElement target = ctx.getInfo().getElements().getTypeElement(targetTypeName);

        if (target == null) {
            return null;
        }

        if (t.isSubtype(t.erasure(coll.asType()), t.erasure(target.asType()))) {
            return null;
        }
        
        List<? extends TypeMirror> assignedTo = CreateElementUtilities.resolveType(EnumSet.noneOf(ElementKind.class), ctx.getInfo(), ctx.getPath().getParentPath(), ctx.getPath().getLeaf(), (int) ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getPath().getCompilationUnit(), ctx.getPath().getLeaf()), new TypeMirror[1], new int[1]);
        
        if (assignedTo != null && assignedTo.size() == 1) {
            if (t.isSubtype(t.erasure(assignedTo.get(0)), t.erasure(coll.asType())))
                return null;
        }
    }

    String displayName = NbBundle.getMessage(Tiny.class, key);

    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName, fixes);
}
 
Example 18
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Map<String, Object> createBindings(TypeElement clazz, ExecutableElement element) {
    CodeStyle cs = DiffContext.getCodeStyle(copy);       
    Map<String, Object> bindings = new HashMap<>();
    if (clazz != null) {
        bindings.put(CLASS_NAME, clazz.getQualifiedName().toString());
        bindings.put(SIMPLE_CLASS_NAME, clazz.getSimpleName().toString());
    }
    if (element != null) {
        bindings.put(METHOD_NAME, element.getSimpleName().toString());
        bindings.put(METHOD_RETURN_TYPE, element.getReturnType().toString()); //NOI18N
        Object value;
        switch(element.getReturnType().getKind()) {
            case BOOLEAN:
                value = "false"; //NOI18N
                break;
            case BYTE:
            case CHAR:
            case DOUBLE:
            case FLOAT:
            case INT:
            case LONG:
            case SHORT:
                value = 0;
                break;
            default:
                value = "null"; //NOI18N
        }
        bindings.put(DEFAULT_RETURN_TYPE_VALUE, value);
    }
    if (clazz != null && element != null) {
        StringBuilder sb = new StringBuilder();
        if (element.isDefault() && element.getEnclosingElement().getKind().isInterface()) {
            Types types = copy.getTypes();
            Context ctx = ((JavacTaskImpl) copy.impl.getJavacTask()).getContext();
            com.sun.tools.javac.code.Types typesImpl = com.sun.tools.javac.code.Types.instance(ctx);
            TypeMirror enclType = typesImpl.asSuper((Type)clazz.asType(), ((Type)element.getEnclosingElement().asType()).tsym);
            if (!types.isSubtype(clazz.getSuperclass(), enclType)) {
                TypeMirror selected = enclType;
                for (TypeMirror iface : clazz.getInterfaces()) {
                    if (types.isSubtype(iface, selected) &&
                        !types.isSameType(iface, enclType)) {
                        selected = iface;
                        break;
                    }
                }
                sb.append(((DeclaredType)selected).asElement().getSimpleName()).append('.');
            }
        }
        sb.append("super.").append(element.getSimpleName()).append('('); //NOI18N
        for (Iterator<? extends VariableElement> it = element.getParameters().iterator(); it.hasNext();) {
            VariableElement ve = it.next();
            sb.append(addParamPrefixSuffix(removeParamPrefixSuffix(ve, cs), cs));
            if (it.hasNext())
                sb.append(","); //NOI18N
        }
        sb.append(')'); //NOI18N
        bindings.put(SUPER_METHOD_CALL, sb);
    }
    return bindings;
}
 
Example 19
Source File: ProcessorUtils.java    From MRouter with Apache License 2.0 4 votes vote down vote up
public static boolean isInActivity(Elements elements, Types types, TypeElement enclosingElement) {
    TypeMirror typeActivity = elements.getTypeElement(Constant.ACTIVITY).asType();
    return types.isSubtype(enclosingElement.asType(), typeActivity);
}
 
Example 20
Source File: AutoUtils.java    From fastjgame with Apache License 2.0 2 votes vote down vote up
/**
 * 忽略两个类型的泛型参数,判断第一个是否是第二个的子类型。
 * 如果考虑泛型的话,会存在区别
 */
public static boolean isSubTypeIgnoreTypeParameter(Types typeUtil, TypeMirror first, TypeMirror second) {
    return typeUtil.isSubtype(typeUtil.erasure(first), typeUtil.erasure(second));
}