private void createOrUpdateFieldHolder(Element element, Elements elements, Types types, JsonObjectHolder objectHolder) { JsonIgnore ignoreAnnotation = element.getAnnotation(JsonIgnore.class); boolean shouldParse = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.SERIALIZE_ONLY; boolean shouldSerialize = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.PARSE_ONLY; if (shouldParse || shouldSerialize) { JsonFieldHolder fieldHolder = objectHolder.fieldMap.get(element.getSimpleName().toString()); if (fieldHolder == null) { fieldHolder = new JsonFieldHolder(); objectHolder.fieldMap.put(element.getSimpleName().toString(), fieldHolder); } String error = fieldHolder.fill(element, elements, types, null, null, objectHolder, shouldParse, shouldSerialize); if (!TextUtils.isEmpty(error)) { error(element, error); } } }
private boolean isOfKindAndType(TypeMirror type, Element e, EnumSet<ElementKind> kinds, TypeMirror base, Scope scope, Trees trees, Types types) { if (type.getKind() != TypeKind.ERROR && kinds.contains(e.getKind())) { if (base == null) return true; if (types.isSubtype(type, base)) return true; } if ((e.getKind().isClass() || e.getKind().isInterface()) && (kinds.contains(ANNOTATION_TYPE) || kinds.contains(CLASS) || kinds.contains(ENUM) || kinds.contains(INTERFACE))) { DeclaredType dt = (DeclaredType)e.asType(); for (Element ee : e.getEnclosedElements()) if (trees.isAccessible(scope, ee, dt) && isOfKindAndType(ee.asType(), ee, kinds, base, scope, trees, types)) return true; } return false; }
/** * Adds a statement creating a new MarkerAnnotation instance to builder. * Returns the name of the instance. * @param builder The builder to add to. * @param annotation The service annotation to gather info from. * @return The name of the new instance. */ public static String addMarkerAnnotationInstance(MethodSpec.Builder builder, UserMarkerAnnotation annotation, Types types, Elements elements) { String siName = ((TypeElement)types.asElement(annotation.getServiceInterfaceType())).getQualifiedName().toString(); builder.addComment("The following values were gathered from the original @Service annotation parameters,"); builder.addComment("and included here for this specialized service processor."); builder.addStatement("$T marker = new $T($S, $S, $S, $S)", MARKER_ANNOTATION_CLASS_NAME, MARKER_ANNOTATION_CLASS_NAME, siName, annotation.getServiceInterfaceName(), annotation.getIndividualNameKey(), annotation.getOutputPackage(elements)); return "marker"; }
private static KindOfType detectKind(CompilationInfo info, TypeMirror tm) { if (tm.getKind().isPrimitive()) { return KindOfType.valueOf(tm.getKind().name()); } if (tm.getKind() == TypeKind.ARRAY) { return ((ArrayType) tm).getComponentType().getKind().isPrimitive() ? KindOfType.ARRAY_PRIMITIVE : KindOfType.ARRAY; } if (tm.getKind() == TypeKind.DECLARED) { Types t = info.getTypes(); TypeElement en = info.getElements().getTypeElement("java.lang.Enum"); if (en != null) { if (t.isSubtype(tm, t.erasure(en.asType()))) { return KindOfType.ENUM; } } if (((DeclaredType)tm).asElement().getKind().isClass() && ((TypeElement) ((DeclaredType) tm).asElement()).getQualifiedName().contentEquals("java.lang.String")) { return KindOfType.STRING; } } return KindOfType.OTHER; }
public void testAddImport14() throws IOException { testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest3.java"); 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.Map.Entry"); Types types = workingCopy.getTypes(); TypeMirror tm = types.getArrayType(types.erasure(list.asType())); stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "entry", make.Type(tm), null)); workingCopy.rewrite(body, make.Block(stats, false)); } }; src.runModificationTask(task).commit(); assertFiles("testAddImport14.pass"); }
public void testAddImportOrder1() throws IOException { testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest7.java"); 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.LinkedList"); Types types = workingCopy.getTypes(); TypeMirror tm = types.getArrayType(types.erasure(list.asType())); stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "s", make.Type(tm), null)); workingCopy.rewrite(body, make.Block(stats, false)); } }; src.runModificationTask(task).commit(); assertFiles("testAddImportOrder1.pass"); }
private boolean isOfKindAndType(TypeMirror type, Element e, EnumSet<ElementKind> kinds, TypeMirror base, Scope scope, Trees trees, Types types) { if (type.getKind() != TypeKind.ERROR && kinds.contains(e.getKind())) { if (base == null) { return true; } if (types.isSubtype(type, base)) { return true; } } if ((e.getKind().isClass() || e.getKind().isInterface()) && (kinds.contains(ANNOTATION_TYPE) || kinds.contains(CLASS) || kinds.contains(ENUM) || kinds.contains(INTERFACE))) { DeclaredType dt = (DeclaredType) e.asType(); for (Element ee : e.getEnclosedElements()) { if (trees.isAccessible(scope, ee, dt) && isOfKindAndType(ee.asType(), ee, kinds, base, scope, trees, types)) { return true; } } } return false; }
public void testGetFirstTypeArgument() throws Exception { ClasspathInfo cpi = ClasspathInfo.create(srcFO); final AnnotationModelHelper helper = AnnotationModelHelper.create(cpi); helper.runJavaSourceTask(new Runnable() { public void run() { Elements elements = helper.getCompilationController().getElements(); Types types = helper.getCompilationController().getTypes(); TypeElement typeElement = elements.getTypeElement("java.util.Collection"); // Collection<E> assertNull(EntityMappingsUtilities.getFirstTypeArgument(typeElement.asType())); // Collection assertNull(EntityMappingsUtilities.getFirstTypeArgument(types.erasure(typeElement.asType()))); // Collection<String> TypeMirror stringType = elements.getTypeElement("java.lang.String").asType(); TypeElement argTypeElement = EntityMappingsUtilities.getFirstTypeArgument(types.getDeclaredType(typeElement, stringType)); assertTrue(argTypeElement.getQualifiedName().contentEquals("java.lang.String")); } }); }
private void checkForUsagesOutsideOfType(final Element target, TreePath currentPath, TreePathHandle elementBeingMoved) { final Types types = workingCopy.getTypes(); TypeMirror targetType = target.asType(); TreePath enclosingPath = JavaRefactoringUtils.findEnclosingClass(workingCopy, currentPath, true, true, true, true, false); Element enclosingEl = null; if(enclosingPath != null) { enclosingEl = workingCopy.getTrees().getElement(enclosingPath); } if(enclosingEl != null) { TypeMirror enclosingType = enclosingEl.asType(); if(!(enclosedBy(targetType, enclosingType) || enclosedBy(enclosingType, targetType)) && !types.isSameType(enclosingType, targetType)) { usageOutsideOfType.put(elementBeingMoved, Boolean.TRUE); } } else { usageOutsideOfType.put(elementBeingMoved, Boolean.TRUE); } }
private ExecutableElement findExecutableMember(TypeElement clazz, String methodName, List<TypeMirror> paramTypes, Types types) { List<ExecutableElement> members = methodName.contentEquals(clazz.getSimpleName()) ? ElementFilter.constructorsIn(clazz.getEnclosedElements()) : ElementFilter.methodsIn(clazz.getEnclosedElements()); outer: for (ExecutableElement ee : members) { if (ee.getKind() == ElementKind.CONSTRUCTOR || methodName.contentEquals(ee.getSimpleName())) { List<? extends TypeMirror> memberParamTypes = ((ExecutableType) ee.asType()).getParameterTypes(); if (memberParamTypes.size() == paramTypes.size()) { Iterator<TypeMirror> it = paramTypes.iterator(); for (TypeMirror memberParamType : memberParamTypes) { TypeMirror type = it.next(); if (types.isSameType(type, memberParamType)) { continue outer; } } return ee; } } } return null; }
@Override public Tree visitTypeCast(TypeCastTree castTree, Element elementToMatch) { TreePath path = getCurrentPath(); Types types = workingCopy.getTypes(); TypeMirror castTypeErasure = types.erasure(workingCopy.getTrees().getTypeMirror(path)); TypeMirror elToMatchErasure = types.erasure(subTypeElement.asType()); path = path.getParentPath(); Element element = workingCopy.getTrees().getElement(path); if (element instanceof VariableElement && types.isSameType(castTypeErasure, elToMatchErasure)) { VariableElement varElement = (VariableElement)element; TypeMirror varTypeErasure = types.erasure(varElement.asType()); if (types.isSameType(varTypeErasure, elToMatchErasure) && isReplaceCandidate(varElement)) { TypeCastTree newTree = make.TypeCast( make.Identifier(superTypeElement), castTree.getExpression()); rewrite(castTree, newTree); } } return super.visitTypeCast(castTree, elementToMatch); }
public static boolean processGlobalSetting(Types mTypes, List<? extends AnnotationMirror> annoMirrors, ProcessorPrinter pp) { for (AnnotationMirror am : annoMirrors) { //if not my want. ignore if (!isValidAnnotation(am, pp)) { continue; } Map<? extends ExecutableElement, ? extends AnnotationValue> methodMap = am.getElementValues(); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> en : methodMap.entrySet()) { ExecutableElement key = en.getKey();//the method of annotation switch (key.getSimpleName().toString()) { case KEY_GSON_CONFIG: { Object value = en.getValue().getValue(); //@GsonConfig AnnotationMirror am2 = (AnnotationMirror) value; handleGsonConfig(am2, pp); } default: //next to do break; } } } return true; }
private static boolean isInTypes(Types types, TypeMirror tm, List<TypeMirror>[] sTypes, int from) { if (from >= sTypes.length) { return true; } for (TypeMirror testTM : sTypes[from]) { if (types.isSameType(tm, testTM)) { return isInTypes(types, tm, sTypes, from + 1); } } return false; }
private void addEffectivelyFinalAutoCloseables(final Env env) throws IOException { final CompilationController controller = env.getController(); final Elements elements = controller.getElements(); final TypeElement te = elements.getTypeElement("java.lang.AutoCloseable"); //NOI18N if (te != null) { final Types types = controller.getTypes(); final ElementUtilities eu = controller.getElementUtilities(); final Scope scope = env.getScope(); final Set<? extends TypeMirror> smartTypes = options.contains(Options.ALL_COMPLETION) ? null : getSmartTypes(env); final TypeElement enclClass = scope.getEnclosingClass(); for (Element e : getLocalMembersAndVars(env)) { switch (e.getKind()) { case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case RESOURCE_VARIABLE: case PARAMETER: if (types.isSubtype(e.asType(), te.asType()) && eu.isEffectivelyFinal((VariableElement) e)) { results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, e.asType(), anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, e.asType(), smartTypes), env.assignToVarPos())); } break; case FIELD: if (types.isSubtype(e.asType(), te.asType())) { String name = e.getSimpleName().toString(); if (THIS_KEYWORD.equals(name) || SUPER_KEYWORD.equals(name)) { results.add(itemFactory.createKeywordItem(name, null, anchorOffset, isOfSmartType(env, e.asType(), smartTypes))); } else { TypeMirror tm = asMemberOf(e, enclClass != null ? enclClass.asType() : null, types); results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, tm, anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, tm, smartTypes), env.assignToVarPos())); } } break; } } } }
public static TargetTypeKind getTargetTypeKind(Elements elements, Types types, TypeElement enclosingElement) { if (isInActivity(elements, types, enclosingElement)) { return TargetTypeKind.ACTIVITY; } if (isInFragment(elements, types, enclosingElement)) { return TargetTypeKind.FRAGMENT; } if (isInProvider(elements, types, enclosingElement)) { return TargetTypeKind.PROVIDER; } return TargetTypeKind.UNKNOWN; }
private Set<MethodSpec> getMethods(Types typeUtils) { Set<MethodSpec> methods = new HashSet<>(); MethodSpec constructor = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(classTypeName, MEMBER_FIELD_NAME) .addStatement("this.$N = $N", MEMBER_FIELD_NAME, MEMBER_FIELD_NAME) .build(); methods.add(constructor); Set<Element> allElements = new HashSet<>(); allElements.addAll(element.getEnclosedElements()); for (TypeMirror typeMirror : element.getInterfaces()) { allElements.addAll(typeUtils.asElement(typeMirror).getEnclosedElements()); } for (Element e : allElements) { if (!(e instanceof ExecutableElement)) { continue; } ExecutableElement method = (ExecutableElement) e; String methodName = method.getSimpleName().toString(); if ("<init>".equals(methodName)) { // skip constructors continue; } Set<Modifier> modifiers = new HashSet<>(method.getModifiers()); if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.STATIC) || modifiers.contains(Modifier.FINAL)) { continue; } modifiers.remove(Modifier.ABSTRACT); modifiers.add(Modifier.SYNCHRONIZED); MethodSpec.Builder spec = MethodSpec.methodBuilder(methodName) .addModifiers(modifiers); List<? extends TypeMirror> thrownTypes = method.getThrownTypes(); for (TypeMirror throwable : thrownTypes) { spec = spec.addException(TypeName.get(throwable)); } String arguments = ""; List<? extends VariableElement> parameters = method.getParameters(); for (VariableElement parameter : parameters) { arguments += parameter.getSimpleName().toString(); if (parameters.indexOf(parameter) != parameters.size() - 1) { arguments += ", "; } spec.addParameter(ParameterSpec.get(parameter)); } if (method.getReturnType() instanceof NoType) { spec = spec.addStatement("$N.$N($L)", MEMBER_FIELD_NAME, methodName, arguments); } else { spec = spec.addStatement("return $N.$N($L)", MEMBER_FIELD_NAME, methodName, arguments) .returns(TypeName.get(method.getReturnType())); } methods.add(spec.build()); } return methods; }
@Nonnull static List<ExecutableElement> getMethods( @Nonnull final TypeElement element, @Nonnull final Types typeUtils ) { final Map<String, ExecutableElement> methodMap = new LinkedHashMap<>(); enumerateMethods( element, typeUtils, element, methodMap ); return new ArrayList<>( methodMap.values() ); }
@Override @NonNull public Collection<? extends String> getFieldNames( @NonNull final String clz, final boolean rt, @NullAllowed final String type) throws QueryException { final TypeElement te = findClass(clz); if (te == null) { return Collections.<String>emptyList(); } final Types types = control.getTypes(); TypeMirror tm = null; if (type != null) { final List<? extends TypeElement> topLevels = control.getTopLevelElements(); tm = topLevels.isEmpty() ? null : control.getTreeUtilities().parseType(type, topLevels.get(0)); if (tm == null) { return Collections.<String>emptyList(); } else if (rt) { tm = types.erasure(tm); } } final Collection<String> result = new ArrayList<String>(); for (VariableElement ve : ElementFilter.fieldsIn(te.getEnclosedElements())) { if (isSameType(types,tm,ve.asType(),rt)) { result.add(ve.getSimpleName().toString()); } } return Collections.unmodifiableCollection(result); }
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; }
public void testGetTypeName() throws Exception { TestUtilities.copyStringToFileObject(testFO, "package foo;" + "public class TestClass {" + "}"); runUserActionTask(testFO, new Task<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); Elements elements = controller.getElements(); Types types = controller.getTypes(); String typeName = String.class.getName(); String resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType()); assertEquals(typeName, resolvedTypeName); typeName = InputStream.class.getName(); resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType()); assertEquals(typeName, resolvedTypeName); resolvedTypeName = MethodModelSupport.getTypeName(types.getPrimitiveType(TypeKind.INT)); assertEquals("int", resolvedTypeName); typeName = String.class.getName(); resolvedTypeName = MethodModelSupport.getTypeName(types.getArrayType(elements.getTypeElement(typeName).asType())); assertEquals("java.lang.String[]", resolvedTypeName); PrimitiveType primitiveType = types.getPrimitiveType(TypeKind.BYTE); ArrayType arrayType = types.getArrayType(primitiveType); resolvedTypeName = MethodModelSupport.getTypeName(arrayType); assertEquals("byte[]", resolvedTypeName); } }); }
public ProcessorElement(Element element, Elements elementUtils, Types typeUtils, Messager messager) { this.element = element; this.elementUtils = elementUtils; this.typeUtils = typeUtils; this.messager = messager; }
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; }
/** * Checks that the given annotation is of type * <code>{@value #ANN_SUITE}.{@value #ANN_SUITE_MEMBERS}</code> * and contains the given list of classes as (the only) argument, * in the same order. * * @param annMirror annotation to be checked * @param suiteMembers list of fully qualified class names denoting * content of the test suite * @return {@code true} if the annotation meets the described criteria, * {@code false} otherwise */ private boolean checkSuiteMembersAnnotation(AnnotationMirror annMirror, List<String> suiteMembers, WorkingCopy workingCopy) { Map<? extends ExecutableElement,? extends AnnotationValue> annParams = annMirror.getElementValues(); if (annParams.size() != 1) { return false; } AnnotationValue annValue = annParams.values().iterator().next(); Object value = annValue.getValue(); if (value instanceof java.util.List) { List<? extends AnnotationValue> items = (List<? extends AnnotationValue>) value; if (items.size() != suiteMembers.size()) { return false; } Types types = workingCopy.getTypes(); Iterator<String> suiteMembersIt = suiteMembers.iterator(); for (AnnotationValue item : items) { Name suiteMemberName = getAnnotationValueClassName(item, types); if (suiteMemberName == null) { return false; } if (!suiteMemberName.contentEquals(suiteMembersIt.next())) { return false; } } return true; } return false; }
/** * Returns fully qualified class name of a class given to an annotation * as (the only) argument. * * @param annValue annotation value * @return fully qualified name of a class represented by the given * annotation value, or {@code null} if the annotation value * does not represent a class */ private Name getAnnotationValueClassName(AnnotationValue annValue, Types types) { Object value = annValue.getValue(); if (value instanceof TypeMirror) { TypeMirror typeMirror = (TypeMirror) value; Element typeElement = types.asElement(typeMirror); if (typeElement.getKind() == ElementKind.CLASS) { return ((TypeElement) typeElement).getQualifiedName(); } } return null; }
public ExpressionTree Type(TypeMirror type) { Type t = (Type) type; JCExpression tp; switch (type.getKind()) { case WILDCARD: { WildcardType a = ((WildcardType) type); tp = make.at(NOPOS).Wildcard(make.at(NOPOS).TypeBoundKind(a.kind), (JCExpression) Type(a.type)); break; } case DECLARED: JCExpression clazz = (JCExpression) QualIdent(t.tsym); tp = t.getTypeArguments().isEmpty() ? clazz : make.at(NOPOS).TypeApply(clazz, Types(t.getTypeArguments())); break; case ARRAY: tp = make.at(NOPOS).TypeArray((JCExpression) Type(((ArrayType) type).getComponentType())); break; case NULL: tp = make.at(NOPOS).Literal(TypeTag.BOT, null); break; case ERROR: tp = make.at(NOPOS).Ident(((ErrorType) type).tsym.name); break; default: return make.at(NOPOS).Type((Type)type); } return tp.setType(t); }
@Nonnull static Map<String, TypeMirror> getFields( @Nonnull final TypeElement element, @Nonnull final Types typeUtils ) { final Map<String, TypeMirror> methodMap = new LinkedHashMap<>(); enumerateFields( element, typeUtils, element, methodMap ); return methodMap; }
private static boolean parseImplClass(Types types, ProcessorPrinter pp, AnnotationMirror am, ImplInfo info) { Map<? extends ExecutableElement, ? extends AnnotationValue> map = am.getElementValues(); pp.note(TAG, "parseImplClass", "am.getElementValues() = map . is " + map); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> en : map.entrySet()) { ExecutableElement key = en.getKey(); if (key.getSimpleName().toString().equals("value")) { TypeMirror tm = (TypeMirror) en.getValue().getValue(); if (!verifyClassName(tm, pp)) { return false; } info.setImplClass(new FieldData.TypeCompat(types, tm)); } } return true; }
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); }
public static boolean isParcelableArray(Types typeUtils, Elements elementUtils, Element element) { if (element.asType().getKind() != TypeKind.ARRAY) { return false; } ArrayType arrayType = (ArrayType) element.asType(); TypeMirror componentType = arrayType.getComponentType(); TypeElement typeParcelable = elementUtils.getTypeElement(Parcelable.class.getName()); return typeUtils.isSubtype(componentType, typeParcelable.asType()); }
private List<Pair<ExecutableElement, ExecutableType>> getMatchingExecutables(TypeMirror type, Iterable<? extends Element> elements, String name, TypeMirror[] argTypes, Types types) { List<Pair<ExecutableElement, ExecutableType>> ret = new ArrayList<>(); for (Element e : elements) { if ((e.getKind() == CONSTRUCTOR || e.getKind() == METHOD) && name.contentEquals(e.getSimpleName())) { List<? extends VariableElement> params = ((ExecutableElement) e).getParameters(); int parSize = params.size(); boolean varArgs = ((ExecutableElement) e).isVarArgs(); if (!varArgs && (parSize < argTypes.length)) { continue; } ExecutableType eType = (ExecutableType) asMemberOf(e, type, types); if (parSize == 0) { ret.add(Pair.of((ExecutableElement) e, eType)); } else { Iterator<? extends TypeMirror> parIt = eType.getParameterTypes().iterator(); TypeMirror param = null; for (int i = 0; i <= argTypes.length; i++) { if (parIt.hasNext()) { param = parIt.next(); if (!parIt.hasNext() && param.getKind() == TypeKind.ARRAY) { param = ((ArrayType) param).getComponentType(); } } else if (!varArgs) { break; } if (i == argTypes.length) { ret.add(Pair.of((ExecutableElement) e, eType)); break; } if (argTypes[i] == null || !types.isAssignable(argTypes[i], param)) { break; } } } } } return ret; }
private TypeSpec generateCode(Types typeUtils) { Modifier[] modifiers = getModifiers(); return TypeSpec.classBuilder(TypeUtils.simpleNameOf(decoratorClassName)) .addModifiers(modifiers) .addField(getMemberField()) .addMethods(getMethods(typeUtils)) .superclass(getSuperclass()) .addSuperinterfaces(getSuperInterfaces()) .build(); }
@Provides @Singleton @Named(DESCRIPTOR_KEY) static Inventory provideDescriptorInventory(@Named(DESCRIPTOR_KEY) final TypeElement descriptorElement, final ClassName outputClassName, final Types types, final Elements elements, final Trees trees, final Messager messager, @Named(TEMPLATE_KEY) Inventory templateInventory, final ImmutableSet<TypeElement> typesToReceiveAnnotations) { return new Inventory(descriptorElement, outputClassName, types, elements, trees, messager, true, templateInventory.rawTypeNameSubstitutions(), typesToReceiveAnnotations); }
private DeclaredType findCommonSubtype(DeclaredType type1, DeclaredType type2, Env<AttrContext> env) { List<DeclaredType> subtypes1 = getSubtypes(type1, env); List<DeclaredType> subtypes2 = getSubtypes(type2, env); if (subtypes1 == null || subtypes2 == null) return null; Types types = info.getTypes(); for (DeclaredType subtype1 : subtypes1) { for (DeclaredType subtype2 : subtypes2) { if (types.isSubtype(subtype1, subtype2)) return subtype1; if (types.isSubtype(subtype2, subtype1)) return subtype2; } } return null; }
@Hint(displayName="#DN_AnnotationProcessors.overridingGetSupportedAnnotations", description="#DESC_AnnotationProcessors.overridingGetSupportedAnnotations", category="rules15") @Messages({/*"DN_AnnotationProcessors.overridingGetSupportedAnnotations=AbstractProcessor.getSupportedAnnotations() is overridden", "DESC_AnnotationProcessors.overridingGetSupportedAnnotations=Overriding Processor.getSupportedAnnotations() may lead to " + "unnecessary classloading during development, and may prevent important optimalizations. " + "consider using @javax.annotation.processing.SupportedAnnotationTypes",*/ "ERR_AnnotationProcessors.overridingGetSupportedAnnotations=AbstractProcessor.getSupportedAnnotationTypes() overridden, may cause performance problems during development"}) @TriggerTreeKind(Kind.CLASS) public static ErrorDescription oGSA(HintContext ctx) { Element clazz = ctx.getInfo().getTrees().getElement(ctx.getPath()); if (clazz == null || !clazz.getKind().isClass()) return null; TypeElement ap = ctx.getInfo().getElements().getTypeElement("javax.annotation.processing.AbstractProcessor"); if (ap == null) return null; Types types = ctx.getInfo().getTypes(); if (!types.isSubtype(types.erasure(clazz.asType()), types.erasure(ap.asType()))) return null; for (ExecutableElement ee : ElementFilter.methodsIn(clazz.getEnclosedElements())) { if (ee.getSimpleName().contentEquals("getSupportedAnnotationTypes") && ee.getParameters().isEmpty()) { Tree t = ctx.getInfo().getTrees().getTree(ee); if (t != null) { return ErrorDescriptionFactory.forName(ctx, t, Bundle.ERR_AnnotationProcessors_overridingGetSupportedAnnotations()); } } } return null; }
public static TypeElement getSuperElement(Types types,Element element){ if (element instanceof TypeElement){ TypeElement typeElement = (TypeElement) element; Element superElement = types.asElement(typeElement.getSuperclass()); return (TypeElement) superElement; } return null; }
private static boolean isSameType ( @NonNull Types types, @NullAllowed final TypeMirror t1, @NonNull final TypeMirror t2, final boolean rawType) { return t1 == null || types.isSameType( t1, rawType ? types.erasure(t2) : t2); }
private TypeMirror getCorrectedReturnType(Env env, ExecutableType et, ExecutableElement el, TypeMirror site) { TypeMirror type = et.getReturnType(); if (site != null && site.getKind() == TypeKind.DECLARED) { if ("getClass".contentEquals(el.getSimpleName()) && et.getParameterTypes().isEmpty() //NOI18N && type.getKind() == TypeKind.DECLARED && JAVA_LANG_CLASS.contentEquals(((TypeElement) ((DeclaredType) type).asElement()).getQualifiedName()) && ((TypeElement) ((DeclaredType) type).asElement()).getTypeParameters().size() == 1) { Types types = env.getController().getTypes(); type = types.getDeclaredType((TypeElement) ((DeclaredType) type).asElement(), types.getWildcardType(site, null)); } } return type; }
public void testAddImport12() 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); TypeElement map = workingCopy.getElements().getTypeElement("java.util.Map"); ClassTree nue = make.addClassImplementsClause(clazz, make.QualIdent(map)); workingCopy.rewrite(clazz, nue); 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.Map.Entry"); Types types = workingCopy.getTypes(); TypeMirror tm = types.getArrayType(types.erasure(list.asType())); stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "entry", make.Type(tm), null)); workingCopy.rewrite(body, make.Block(stats, false)); } }; src.runModificationTask(task).commit(); assertFiles("testAddImport12.pass"); }
private static TypeMirror findUnion(Types types, List<TypeMirror>[] sTypes) { for (TypeMirror tm : sTypes[0]) { if (isInTypes(types, tm, sTypes, 1)) { return tm; } } return null; }