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

The following examples show how to use javax.lang.model.util.Types#getDeclaredType() . 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: TypeMirrors.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a parameterised generic type.
 *
 * @throws IllegalArgumentException if {@code rawType} is not in fact a raw type, or if
 *     the number of given parameters does not match the number declared on the raw type.
 */
private static DeclaredType parameterisedType(
    Types typeUtils,
    TypeMirror rawType,
    List<TypeMirror> paramTypes) {
  Preconditions.checkArgument(
      rawType.getKind() == TypeKind.DECLARED
          && ((DeclaredType) rawType).getTypeArguments().isEmpty(),
      "Expected raw type, got '%s'",
      rawType);
  TypeElement genericType = (TypeElement) typeUtils.asElement(rawType);
  Preconditions.checkArgument(
      genericType.getTypeParameters().size() == paramTypes.size(),
      "Incorrect number of arguments for %s (expected %s, got %s)",
      genericType,
      genericType.getTypeParameters().size(),
      paramTypes.size());
  DeclaredType declaredType = typeUtils.getDeclaredType(
      genericType, paramTypes.toArray(new TypeMirror[paramTypes.size()]));
  return declaredType;
}
 
Example 2
Source File: RetroFacebookProcessor.java    From RetroFacebook with Apache License 2.0 6 votes vote down vote up
public String buildCallbackType(ExecutableElement method) {
  Types typeUtils = processingEnv.getTypeUtils();
  TypeMirror callback = getTypeMirror(processingEnv, RetroFacebook.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 3
Source File: ImportAnalysisTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAddImport3() throws IOException {
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree node = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = node.getBody();
            List<StatementTree> stats = new ArrayList<StatementTree>();
            for (StatementTree st : body.getStatements()) {
                stats.add(st);
            }
            TypeElement list = workingCopy.getElements().getTypeElement("java.util.List");
            TypeElement collection = workingCopy.getElements().getTypeElement("java.util.Collection");
            Types types = workingCopy.getTypes();
            TypeMirror tm = types.getDeclaredType(list, types.erasure(collection.asType()));
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "utilList", make.Type(tm), null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testAddImport3.pass");
}
 
Example 4
Source File: ImportAnalysisTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAddImport4() throws IOException {
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree node = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = node.getBody();
            List<StatementTree> stats = new ArrayList<StatementTree>();
            for (StatementTree st : body.getStatements()) {
                stats.add(st);
            }
            TypeElement list = workingCopy.getElements().getTypeElement("java.util.List");
            TypeElement collection = workingCopy.getElements().getTypeElement("java.util.Collection");
            Types types = workingCopy.getTypes();
            TypeMirror tm = types.getDeclaredType(list, types.getWildcardType(types.erasure(collection.asType()), null));
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "utilList", make.Type(tm), null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testAddImport4.pass");
}
 
Example 5
Source File: ApNavigator.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public TypeMirror erasure(TypeMirror t) {
    Types tu = env.getTypeUtils();
    t = tu.erasure(t);
    if (t.getKind().equals(TypeKind.DECLARED)) {
        DeclaredType dt = (DeclaredType)t;
        if (!dt.getTypeArguments().isEmpty())
            return tu.getDeclaredType((TypeElement) dt.asElement());
    }
    return t;
}
 
Example 6
Source File: ApNavigator.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public TypeMirror erasure(TypeMirror t) {
    Types tu = env.getTypeUtils();
    t = tu.erasure(t);
    if (t.getKind().equals(TypeKind.DECLARED)) {
        DeclaredType dt = (DeclaredType)t;
        if (!dt.getTypeArguments().isEmpty())
            return tu.getDeclaredType((TypeElement) dt.asElement());
    }
    return t;
}
 
Example 7
Source File: MakeSafeTypeVisitor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TypeMirror visitDeclared(DeclaredType t, Types types) {
    if (TypeModeler.isSubElement((TypeElement) t.asElement(), collectionType)
            || TypeModeler.isSubElement((TypeElement) t.asElement(), mapType)) {
        Collection<? extends TypeMirror> args = t.getTypeArguments();
        TypeMirror[] safeArgs = new TypeMirror[args.size()];
        int i = 0;
        for (TypeMirror arg : args) {
            safeArgs[i++] = visit(arg, types);
        }
        return types.getDeclaredType((TypeElement) t.asElement(), safeArgs);
    }
    return types.erasure(t);
}
 
Example 8
Source File: MakeSafeTypeVisitor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TypeMirror visitDeclared(DeclaredType t, Types types) {
    if (TypeModeler.isSubElement((TypeElement) t.asElement(), collectionType)
            || TypeModeler.isSubElement((TypeElement) t.asElement(), mapType)) {
        Collection<? extends TypeMirror> args = t.getTypeArguments();
        TypeMirror[] safeArgs = new TypeMirror[args.size()];
        int i = 0;
        for (TypeMirror arg : args) {
            safeArgs[i++] = visit(arg, types);
        }
        return types.getDeclaredType((TypeElement) t.asElement(), safeArgs);
    }
    return types.erasure(t);
}
 
Example 9
Source File: Utils.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
/**
 * A singleton is defined by a class with a public static final field named "INSTANCE"
 * with a type assignable from a {@code TypeAdapter} of {@code adaptedType}.
 */
static boolean isSingletonAdapter(
    Elements elements, Types types, TypeElement element, TypeMirror adaptedType) {
  TypeElement typeAdapterElement = elements.getTypeElement(TYPE_ADAPTER_CLASS_NAME);
  DeclaredType typeAdapterType = types.getDeclaredType(typeAdapterElement, adaptedType);
  return isSingleton(types, element, typeAdapterType);
}
 
Example 10
Source File: MultisetProperty.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
private static TypeMirror multiset(
    TypeMirror elementType,
    Elements elements,
    Types types) {
  TypeElement multisetType = elements.getTypeElement(Multiset.class.getName());
  return types.getDeclaredType(multisetType, elementType);
}
 
Example 11
Source File: MakeSafeTypeVisitor.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TypeMirror visitDeclared(DeclaredType t, Types types) {
    if (TypeModeler.isSubElement((TypeElement) t.asElement(), collectionType)
            || TypeModeler.isSubElement((TypeElement) t.asElement(), mapType)) {
        Collection<? extends TypeMirror> args = t.getTypeArguments();
        TypeMirror[] safeArgs = new TypeMirror[args.size()];
        int i = 0;
        for (TypeMirror arg : args) {
            safeArgs[i++] = visit(arg, types);
        }
        return types.getDeclaredType((TypeElement) t.asElement(), safeArgs);
    }
    return types.erasure(t);
}
 
Example 12
Source File: ApNavigator.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public TypeMirror erasure(TypeMirror t) {
    Types tu = env.getTypeUtils();
    t = tu.erasure(t);
    if (t.getKind().equals(TypeKind.DECLARED)) {
        DeclaredType dt = (DeclaredType)t;
        if (!dt.getTypeArguments().isEmpty())
            return tu.getDeclaredType((TypeElement) dt.asElement());
    }
    return t;
}
 
Example 13
Source File: CompilationRuleTest.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
/**
 * Do some non-trivial operation with {@link TypeMirror} instances because they stop working after
 * compilation stops.
 */
@Test public void typeMirrorsAreValidAndWorking() {
  Elements elements = compilationRule.getElements();
  Types types = compilationRule.getTypes();
  DeclaredType arrayListOfString = types.getDeclaredType(
      elements.getTypeElement(ArrayList.class.getName()),
      elements.getTypeElement(String.class.getName()).asType());
  DeclaredType listOfExtendsObjectType = types.getDeclaredType(
      elements.getTypeElement(List.class.getName()),
      types.getWildcardType(elements.getTypeElement(Object.class.getName()).asType(), null));
  assertThat(types.isAssignable(arrayListOfString, listOfExtendsObjectType)).isTrue();
}
 
Example 14
Source File: ElementUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private DeclaredType getDeclaredType(TypeElement e, HashMap<? extends Element, ? extends TypeMirror> map, Types types) {
    List<? extends TypeParameterElement> tpes = e.getTypeParameters();
    TypeMirror[] targs = new TypeMirror[tpes.size()];
    int i = 0;
    for (Iterator<? extends TypeParameterElement> it = tpes.iterator(); it.hasNext();) {
        TypeParameterElement tpe = it.next();
        TypeMirror t = map.get(tpe);
        targs[i++] = t != null ? t : tpe.asType();
    }
    Element encl = e.getEnclosingElement();
    if ((encl.getKind().isClass() || encl.getKind().isInterface()) && !((TypeElement)encl).getTypeParameters().isEmpty())
            return types.getDeclaredType(getDeclaredType((TypeElement)encl, map, types), e, targs);
    return types.getDeclaredType(e, targs);
}
 
Example 15
Source File: ExceptionCompletionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<DeclaredType> fillSubTypes(CompilationController cc, DeclaredType dType) {
    List<DeclaredType> subtypes = new ArrayList<>();
    //Set<? extends SearchScopeType> scope = Collections.singleton(new ClassSearchScopeType(prefix));
    Types types = cc.getTypes();
    if (prefix != null && prefix.length() > 2 && lastPrefixDot < 0) {
        //Trees trees = cc.getTrees();
        ClassIndex.NameKind kind = ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX;
        for (ElementHandle<TypeElement> handle : cpi.getClassIndex().getDeclaredTypes(prefix, kind, EnumSet.allOf(ClassIndex.SearchScope.class))) {
            TypeElement te = handle.resolve(cc);
            if (te != null && /*trees.isAccessible(scope, te) &&*/ types.isSubtype(types.getDeclaredType(te), dType)) {
                subtypes.add(types.getDeclaredType(te));
            }
        }
    } else {
        HashSet<TypeElement> elems = new HashSet<>();
        LinkedList<DeclaredType> bases = new LinkedList<>();
        bases.add(dType);
        ClassIndex index = cpi.getClassIndex();
        while (!bases.isEmpty()) {
            DeclaredType head = bases.remove();
            TypeElement elem = (TypeElement) head.asElement();
            if (!elems.add(elem)) {
                continue;
            }
            if (accept(elem)) {
                subtypes.add(head);
            }
            //List<? extends TypeMirror> tas = head.getTypeArguments();
            //boolean isRaw = !tas.iterator().hasNext();
            for (ElementHandle<TypeElement> eh : index.getElements(ElementHandle.create(elem), EnumSet.of(ClassIndex.SearchKind.IMPLEMENTORS), EnumSet.allOf(ClassIndex.SearchScope.class))) {
                TypeElement e = eh.resolve(cc);
                if (e != null) {
                    DeclaredType dt = types.getDeclaredType(e);
                    bases.add(dt);
                }
            }
        }
    }
    return subtypes;
}
 
Example 16
Source File: ApNavigator.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public TypeMirror erasure(TypeMirror t) {
    Types tu = env.getTypeUtils();
    t = tu.erasure(t);
    if (t.getKind().equals(TypeKind.DECLARED)) {
        DeclaredType dt = (DeclaredType)t;
        if (!dt.getTypeArguments().isEmpty())
            return tu.getDeclaredType((TypeElement) dt.asElement());
    }
    return t;
}
 
Example 17
Source File: Utils.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
/** Returns true if {@code element} is a {@code TypeAdapter} type. */
static boolean isAdapterType(Element element, Elements elements, Types types) {
  TypeMirror typeAdapterType = types.getDeclaredType(
      elements.getTypeElement(TYPE_ADAPTER_CLASS_NAME),
      types.getWildcardType(null, null));
  return types.isAssignable(element.asType(), typeAdapterType);
}
 
Example 18
Source File: JavaHintsAnnotationProcessor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean verifyHintMethod(ExecutableElement method) {
    StringBuilder error = new StringBuilder();
    Elements elements = processingEnv.getElementUtils();
    TypeElement errDesc = elements.getTypeElement("org.netbeans.spi.editor.hints.ErrorDescription");
    TypeElement jlIterable = elements.getTypeElement("java.lang.Iterable");
    TypeElement hintCtx = elements.getTypeElement("org.netbeans.spi.java.hints.HintContext");

    if (errDesc == null || jlIterable == null || hintCtx == null) {
        return true;
    }

    Types types = processingEnv.getTypeUtils();
    TypeMirror errDescType = errDesc.asType(); //no type params, no need to erasure
    TypeMirror jlIterableErrDesc = types.getDeclaredType(jlIterable, errDescType);
    TypeMirror ret = method.getReturnType();

    if (!types.isSameType(ret, errDescType) && !types.isAssignable(ret, jlIterableErrDesc)) {
        error.append(ERR_RETURN_TYPE);
        error.append("\n");
    }

    if (method.getParameters().size() != 1 || !types.isSameType(method.getParameters().get(0).asType(), hintCtx.asType())) {
        error.append(ERR_PARAMETERS);
        error.append("\n");
    }

    if (!method.getModifiers().contains(Modifier.STATIC)) {
        error.append(ERR_MUST_BE_STATIC);
        error.append("\n");
    }

    if (error.length() == 0) {
        return true;
    }

    if (error.charAt(error.length() - 1) == '\n') {
        error.delete(error.length() - 1, error.length());
    }

    processingEnv.getMessager().printMessage(Kind.ERROR, error.toString(), method);

    return false;
}
 
Example 19
Source File: BindingFieldHelper.java    From AutoBundle with Apache License 2.0 4 votes vote down vote up
static String getOperationName(TypeName target, Elements elements, Types types) {
    if (fieldTypes.containsKey(target)) {
        return fieldTypes.get(target);
    }
    if (target.isBoxedPrimitive()) {
        TypeName unboxed = target.unbox();
        if (fieldTypes.containsKey(unboxed)) {
            return fieldTypes.get(unboxed);
        }
    }

    // Array
    TypeMirror parcelable = elements.getTypeElement("android.os.Parcelable").asType();
    if (target.toString().endsWith("[]")) {
        String removed = target.toString().substring(0, target.toString().length() - 2);
        for (TypeName arrayType : fieldArrayTypes.keySet()) {
            if (removed.equals(arrayType.toString())) {
                return fieldArrayTypes.get(arrayType);
            }
        }
        // Parcelable[]
        TypeElement element = elements.getTypeElement(removed);
        if (element != null && types.isAssignable(element.asType(), parcelable)) {
            return "ParcelableArray";
        }
    }

    String[] splits = detectTypeArgument(target.toString());
    TypeMirror targetType;
    if (splits.length == 1) {
        targetType = elements.getTypeElement(target.toString()).asType();
    } else {
        TypeElement genericType = elements.getTypeElement(splits[0]);
        TypeMirror argType = elements.getTypeElement(splits[1]).asType();
        targetType = types.getDeclaredType(genericType, argType);
    }

    // Parcelable
    if (types.isAssignable(targetType, parcelable)) {
        return "Parcelable";
    }

    // ArrayList<? extend Parcelable>
    TypeElement arrayList = elements.getTypeElement(ArrayList.class.getName());
    TypeMirror wildCardParcelable = types.getWildcardType(parcelable, null);
    TypeMirror parcelableArrayList = types.getDeclaredType(arrayList, wildCardParcelable);
    if (types.isAssignable(targetType, parcelableArrayList)) {
        return "ParcelableArrayList";
    }

    // SparseArray<? extend Parcelable>
    TypeElement sparseArray = elements.getTypeElement("android.util.SparseArray");
    TypeMirror sparceParcelableArray = types.getDeclaredType(sparseArray, wildCardParcelable);
    if (types.isAssignable(targetType, sparceParcelableArray)) {
        return "SparseParcelableArray";
    }

    // IBinder
    TypeMirror iBinder = elements.getTypeElement("android.os.IBinder").asType();
    if (types.isAssignable(targetType, iBinder)) {
        return "Binder";
    }

    // Serializable
    TypeMirror serializable = elements.getTypeElement(Serializable.class.getName()).asType();
    if (types.isAssignable(targetType, serializable)) {
        return "Serializable";
    }

    return null;
}
 
Example 20
Source File: TypeVariables.java    From auto with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a map from methods to return types, where the return types are not necessarily the
 * original return types of the methods. Consider this example:
 *
 * <pre>
 * &#64;AutoValue class {@code Foo<T>} {
 *   abstract T getFoo();
 *
 *   &#64;AutoValue.Builder
 *   abstract class {@code Builder<T>} {
 *     abstract Builder setFoo(T t);
 *     abstract {@code Foo<T>} build();
 *   }
 * }
 * </pre>
 *
 * We want to be able to check that the parameter type of {@code setFoo} is the same as the
 * return type of {@code getFoo}. But in fact it isn't, because the {@code T} of {@code Foo<T>}
 * is not the same as the {@code T} of {@code Foo.Builder<T>}. So we create a parallel
 * {@code Foo<T>} where the {@code T} <i>is</i> the one from {@code Foo.Builder<T>}. That way the
 * types do correspond. This method then returns the return types of the given methods as they
 * appear in that parallel class, meaning the type given for {@code getFoo()} is the {@code T} of
 * {@code Foo.Builder<T>}.
 *
 * <p>We do the rewrite this way around (applying the type parameter from {@code Foo.Builder} to
 * {@code Foo}) because if we hit one of the historical Eclipse bugs with {@link Types#asMemberOf}
 * then {@link EclipseHack#methodReturnType} can use fallback logic, which only works for methods
 * with no arguments.
 *
 * @param methods the methods whose return types are to be rewritten.
 * @param sourceType the class containing those methods ({@code Foo} in the example).
 * @param targetType the class to translate the methods into ({@code Foo.Builder<T>}) in the
 *     example.
 */
static ImmutableMap<ExecutableElement, TypeMirror> rewriteReturnTypes(
    Elements elementUtils,
    Types typeUtils,
    Collection<ExecutableElement> methods,
    TypeElement sourceType,
    TypeElement targetType) {
  List<? extends TypeParameterElement> sourceTypeParameters = sourceType.getTypeParameters();
  List<? extends TypeParameterElement> targetTypeParameters = targetType.getTypeParameters();
  Preconditions.checkArgument(
      sourceTypeParameters.toString().equals(targetTypeParameters.toString()),
      "%s != %s",
      sourceTypeParameters,
      targetTypeParameters);
  // What we're doing is only valid if the type parameters are "the same". The check here even
  // requires the names to be the same. The logic would still work without that, but we impose
  // that requirement elsewhere and it means we can check in this simple way.
  EclipseHack eclipseHack = new EclipseHack(elementUtils, typeUtils);
  TypeMirror[] targetTypeParameterMirrors = new TypeMirror[targetTypeParameters.size()];
  for (int i = 0; i < targetTypeParameters.size(); i++) {
    targetTypeParameterMirrors[i] = targetTypeParameters.get(i).asType();
  }
  DeclaredType parallelSource = typeUtils.getDeclaredType(sourceType, targetTypeParameterMirrors);
  return methods.stream()
      .collect(
          ImmutableMap.toImmutableMap(
              m -> m, m -> eclipseHack.methodReturnType(m, parallelSource)));
}