private MethodSpec generateAsMethod(String generatedCodePackageName, TypeSpec requestBuilder) { TypeVariableName resourceType = TypeVariableName.get("ResourceType"); ParameterizedTypeName classOfResouceType = ParameterizedTypeName .get(ClassName.get(Class.class), resourceType); ClassName generatedRequestBuilderClassName = ClassName.get(generatedCodePackageName, requestBuilder.name); ParameterizedTypeName requestBuilderOfResourceType = ParameterizedTypeName .get(generatedRequestBuilderClassName, resourceType); return MethodSpec.methodBuilder("as") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addTypeVariable(TypeVariableName.get("ResourceType")) .addParameter(classOfResouceType, "resourceClass") .returns(requestBuilderOfResourceType) .addStatement("return new $T<>(glide, this, resourceClass)", this.generatedRequestBuilderClassName) .build(); }
private MethodSpec generateAsMethod(String generatedCodePackageName, TypeSpec requestBuilder) { TypeVariableName resourceType = TypeVariableName.get("ResourceType"); ParameterizedTypeName classOfResouceType = ParameterizedTypeName .get(ClassName.get(Class.class), resourceType); ClassName generatedRequestBuilderClassName = ClassName.get(generatedCodePackageName, requestBuilder.name); ParameterizedTypeName requestBuilderOfResourceType = ParameterizedTypeName .get(generatedRequestBuilderClassName, resourceType); return MethodSpec.methodBuilder("as") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addTypeVariable(TypeVariableName.get("ResourceType")) .addParameter(classOfResouceType, "resourceClass") .addAnnotation(AnnotationSpec.builder(CHECK_RESULT_CLASS_NAME).build()) .returns(requestBuilderOfResourceType) .addStatement("return new $T<>(glide, this, resourceClass, context)", this.generatedRequestBuilderClassName) .build(); }
private static ClassName writeConsumer(int count) throws IOException { String packageName = "info.dourok.esactivity.function"; MethodSpec.Builder method = MethodSpec.methodBuilder("accept") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT); TypeSpec.Builder type = TypeSpec.interfaceBuilder("Consumer" + count) .addModifiers(Modifier.PUBLIC); for (int i = 0; i < count; i++) { type.addTypeVariable(TypeVariableName.get("T" + i)); method.addParameter( TypeVariableName.get("T" + i), "t" + i); } type.addMethod(method.build()); JavaFile.builder(packageName, type.build()) .build() .writeTo(EasyUtils.getFiler()); return ClassName.get(packageName, "Consumer" + count); }
private MethodSpec.Builder createFoldSignature(Iterable<TypeVariableName> availableTypeVariables) throws ParserException { MethodSpec.Builder builder = MethodSpec.methodBuilder("map") .addTypeVariable(FOLD_RETURN_TYPE) .addModifiers(Modifier.PUBLIC) .returns(FOLD_RETURN_TYPE); for (OutputValue arg : values) { TypeName visitor = ParameterizedTypeName.get( ClassName.get(Function.class), TypeVariableUtils.withoutMissingTypeVariables( arg.parameterizedOutputClass(), availableTypeVariables), FOLD_RETURN_TYPE); builder.addParameter( ParameterSpec.builder(visitor, asCamelCase(arg.name())) .addAnnotation(Nonnull.class) .build()); } return builder; }
private MethodSpec.Builder createFoldVoidSignature( Iterable<TypeVariableName> availableTypeVariables) throws ParserException { MethodSpec.Builder builder = MethodSpec.methodBuilder("match").addModifiers(Modifier.PUBLIC).returns(void.class); for (OutputValue arg : values) { TypeName visitor = ParameterizedTypeName.get( ClassName.get(Consumer.class), withoutMissingTypeVariables(arg.parameterizedOutputClass(), availableTypeVariables)); builder.addParameter( ParameterSpec.builder(visitor, asCamelCase(arg.name())) .addAnnotation(Nonnull.class) .build()); } return builder; }
static OutputValue create(Value value, ClassName specOutputClass, Spec spec) throws ParserException { ClassName outputClass = specOutputClass.nestedClass(value.name()); Iterable<TypeVariableName> typeVariables = getTypeVariables(value, spec.typeVariables()); List<Parameter> parameters = new ArrayList<>(); for (Parameter parameter : value.parameters()) { TypeName rawParamType = withoutTypeParameters(parameter.type()); if (isDataEnumParameter(rawParamType)) { TypeName paramOutputType = withParametersFromOther(toOutputClass(rawParamType), parameter.type()); parameters.add(new Parameter(parameter.name(), paramOutputType, parameter.canBeNull())); } else { parameters.add(parameter); } } return new OutputValue(outputClass, value.name(), parameters, typeVariables); }
private static boolean typeNeedsTypeVariable(TypeName type, TypeVariableName typeVariable) { if (typeVariable.equals(type)) { return true; } if (type instanceof ParameterizedTypeName) { ParameterizedTypeName parameterized = ((ParameterizedTypeName) type); for (TypeName typeArgument : parameterized.typeArguments) { if (typeVariable.equals(typeArgument)) { return true; } } } if (type instanceof ArrayTypeName) { ArrayTypeName arrayType = (ArrayTypeName) type; if (typeVariable.equals(arrayType.componentType)) { return true; } } return false; }
private static TypeName getSuperclassForValue(OutputValue value, OutputSpec spec) throws ParserException { if (!spec.hasTypeVariables()) { return spec.outputClass(); } List<TypeName> superParameters = new ArrayList<>(); for (TypeVariableName typeVariable : spec.typeVariables()) { if (Iterables.contains(value.typeVariables(), typeVariable)) { superParameters.add(typeVariable); } else { if (typeVariable.bounds.size() == 0) { superParameters.add(TypeName.OBJECT); } else if (typeVariable.bounds.size() == 1) { superParameters.add(typeVariable.bounds.get(0)); } else { throw new ParserException("More than one generic type bound is not supported "); } } } return ParameterizedTypeName.get( spec.outputClass(), superParameters.toArray(new TypeName[] {})); }
private static MethodSpec createAsSpecMethod(OutputValue value, OutputSpec spec) { List<TypeVariableName> missingTypeVariables = extractMissingTypeVariablesForValue(value, spec); Builder builder = MethodSpec.methodBuilder("as" + spec.outputClass().simpleName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(spec.parameterizedOutputClass()) .addTypeVariables(missingTypeVariables) .addStatement("return ($T) this", spec.parameterizedOutputClass()); // if there are type variables that this sub-type doesn't use, they will lead to 'unchecked // cast' // warnings when compiling the generated code. These warnings are safe to suppress, since this // sub type will never use those type variables. if (!missingTypeVariables.isEmpty()) { builder.addAnnotation(SUPPRESS_UNCHECKED_WARNINGS); } return builder.build(); }
public static Spec parse(Element element, ProcessingEnvironment processingEnv) { Messager messager = processingEnv.getMessager(); if (element.getKind() != ElementKind.INTERFACE) { messager.printMessage( Diagnostic.Kind.ERROR, "@DataEnum can only be used on interfaces.", element); return null; } TypeElement dataEnum = (TypeElement) element; List<TypeVariableName> typeVariableNames = new ArrayList<>(); for (TypeParameterElement typeParameterElement : dataEnum.getTypeParameters()) { typeVariableNames.add(TypeVariableName.get(typeParameterElement)); } List<Value> values = ValuesParser.parse(dataEnum, processingEnv); if (values == null) { return null; } ClassName enumInterface = ClassName.get(dataEnum); return new Spec(enumInterface, typeVariableNames, values); }
private TypeSpec createJsArrayInterface() { TypeVariableName variableName = TypeVariableName.get("T"); return TypeSpec.classBuilder("JsArray") .addModifiers(Modifier.STATIC, Modifier.FINAL) .addTypeVariable(variableName) .addAnnotation(AnnotationSpec.builder(ClassNames.JSINTEROP_JSTYPE) .addMember("isNative", "true") .addMember("namespace", "$T.GLOBAL", ClassNames.JSINTEROP_JSPACKAGE) .addMember("name", "$S", "Array") .build()) .addMethod(MethodSpec.methodBuilder("push") .addModifiers(Modifier.PUBLIC, Modifier.NATIVE) .addParameter(variableName, "item") .build()) .build(); }
@Override public TypeName replaceReturnType(String currentPkg, String directParentInterface, String curClassname, List<? extends TypeMirror> superInterfaces, TypeName superClass, ExecutableElement method) { final TypeMirror returnType = method.getReturnType(); switch (method.getSimpleName().toString()){ case TypeCopyableFiller.NAME_COPY: { switch (returnType.getKind()) { case TYPEVAR: //泛型 return TypeVariableName.get(directParentInterface); default: return TypeName.get(returnType); } } default: return TypeName.get(returnType); } }
/** * Static factory for creating a {@link MethodSignature} from an * {@link ExecutableElement} and a function that can perform type * substitutions on a {@link TypeMirror}, returning a {@link TypeName} * instance. * * @param element * @param substitutor * @return */ public static MethodSignature fromExecutableElementWithSubstitutor(final ExecutableElement element, Function<TypeMirror,TypeName> substitutor) { return builder() .setName(simpleName(element)) .setVarargs(element.isVarArgs()) .setReturns(substitutor.apply(element.getReturnType())) .setIsStatic(Util.isStatic(element)) .addParameters(element.getParameters().stream() .map(VariableElement::asType) .map(substitutor) .collect(toList())) .addExceptions(element.getThrownTypes().stream() .map(substitutor) .collect(toList())) .addTypeParameters(element.getTypeParameters().stream() .map(param -> TypeVariableName.get(simpleName(param)) .withBounds(param.getBounds().stream() .map(substitutor) .collect(toList()))) .collect(toList())) .build(); }
public static MethodSignature fromExecutableElement(final ExecutableElement element) { return builder() .setName(simpleName(element)) .setVarargs(element.isVarArgs()) .setReturns(TypeName.get(element.getReturnType())) .setIsStatic(Util.isStatic(element)) .addParameters(element.getParameters().stream() .map(VariableElement::asType) .map(TypeName::get) .collect(toList())) .addExceptions(element.getThrownTypes().stream() .map(TypeName::get) .collect(toList())) .addTypeParameters(element.getTypeParameters().stream() .map(param -> TypeVariableName.get(simpleName(param)) .withBounds(param.getBounds().stream() .map(TypeName::get) .collect(toList()))) .collect(toList())) .build(); }
private static MethodSpec.Builder getDeployMethodSpec( String className, Class authType, String authName, boolean isPayable) { MethodSpec.Builder builder = MethodSpec.methodBuilder("deploy") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns( buildRemoteCall(TypeVariableName.get(className, Type.class))) .addParameter(Web3j.class, WEB3J) .addParameter(authType, authName) .addParameter(BigInteger.class, GAS_PRICE) .addParameter(BigInteger.class, GAS_LIMIT); if (isPayable) { return builder.addParameter(BigInteger.class, INITIAL_VALUE); } else { return builder; } }
private MethodSpec generateGetterMethod(List<TypeElement> getterMethodBucket, int index) { TypeVariableName t = TypeVariableName.get("T"); MethodSpec.Builder getMethod = MethodSpec.methodBuilder(registryInjectionTarget.getterName + "Bucket" + index) .addTypeVariable(t) .addModifiers(Modifier.PRIVATE) .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class), t), "clazz") .addParameter(String.class, "className") .returns(ParameterizedTypeName.get(ClassName.get(registryInjectionTarget.type), t)); CodeBlock.Builder switchBlockBuilder = CodeBlock.builder().beginControlFlow("switch(className)"); String typeSimpleName = registryInjectionTarget.type.getSimpleName(); for (TypeElement injectionTarget : getterMethodBucket) { switchBlockBuilder.add("case ($S):" + LINE_SEPARATOR, getGeneratedFQNClassName(injectionTarget)); switchBlockBuilder.addStatement("return ($L<T>) new $L$$$$$L()", typeSimpleName, getGeneratedFQNClassName(injectionTarget), typeSimpleName); } switchBlockBuilder.add("default:" + LINE_SEPARATOR); switchBlockBuilder.addStatement("return $L(clazz)", registryInjectionTarget.childrenGetterName); switchBlockBuilder.endControlFlow(); getMethod.addCode(switchBlockBuilder.build()); return getMethod.build(); }
public RuntimePermissionsElement(TypeElement element, TypeResolver resolver) { mTypeResolver = resolver; mTypeName = TypeName.get(element.asType()); typeVariables = new ArrayList<>(); List<? extends TypeParameterElement> typeParameters = element.getTypeParameters(); for (TypeParameterElement element1 : typeParameters) { typeVariables.add(TypeVariableName.get(element1)); } String claseName = element.getQualifiedName().toString(); packageName = ProcessorUtil.getPackageName(claseName); className = ProcessorUtil.getClassName(claseName); classType = checkActivity(element, resolver); generatedClassName = element.getSimpleName().toString() + ConstantsProvider.GEN_CLASS_SUFFIX; needsPermissionsMethods = findMethods(element, NeedsPermission.class); validateNeedsMethods(); showsRationaleMethods = findMethods(element, OnShowRationale.class); validateRationaleMethods(); deniedPermissionMethods = findMethods(element, OnPermissionDenied.class); validateDeniedMethods(); neverAskMethods = findMethods(element, OnNeverAskAgain.class); validateNeverAskMethods(); }
public void generateBinder(LifeCycleAwareInfo lifeCycleAwareInfo) { TypeElement hostElement = lifeCycleAwareInfo.element; PackageElement packageElement = processingEnv.getElementUtils().getPackageOf(hostElement); final String simpleClassName = hostElement.getSimpleName().toString() + LIFE_CYCLE_BINDER_SUFFIX; final String qualifiedClassName = packageElement.getQualifiedName() + "." + simpleClassName; try { JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile( qualifiedClassName, lifeCycleAwareInfo.element); TypeName objectGenericType = TypeName.get(hostElement.asType()); TypeSpec.Builder builder = TypeSpec.classBuilder(simpleClassName) .addModifiers(PUBLIC) .addMethod(generateBindMethod(lifeCycleAwareInfo, objectGenericType)); List<TypeName> typeArguments = TypeUtils.getTypeArguments(hostElement.asType()); for (TypeName argument : typeArguments) { builder.addTypeVariable((TypeVariableName) argument); } writeFile(packageElement, sourceFile, builder.build()); } catch (IOException e) { throw new RuntimeException("Failed writing class file " + qualifiedClassName, e); } }
private static List<Parameter> expand(List<TypeName> typevars, char prefix) { List<TypeName> builder = powerize(typevars); Collections.shuffle(builder); List<Parameter> parameters = new ArrayList<>(builder.size()); int[] count = new int[typevars.size()]; int mapcount = 0; for (TypeName type : builder) { if (type instanceof TypeVariableName) { int idx = typevars.indexOf(type); parameters.add(new Parameter(type, prefix + type.toString().toLowerCase() + count[idx]++)); } else { parameters.add(new Parameter(type, "map" + mapcount++)); } } return parameters; }
private int getFactoryProxyIndex(TypeName gtname) throws AnnotationProcessingException { int ret = -1; boolean found = false; if (gtname instanceof TypeVariableName) { for (TypeParameterElement tpe : m_elem.getTypeParameters()) { ++ret; if (tpe.toString().equals(gtname.toString())) { found = true; break; } } if (!found) { throw new AnnotationProcessingException(null, "%s type is not found during factory proxy query.", gtname.toString()); } } else { throw new AnnotationProcessingException(null, "%s type is not generic type for factory proxy query.", gtname.toString()); } return ret; }
private MethodSpec generateGetUpdaterMethod(FieldSpec mapField) { TypeVariableName typeVariableName = TypeVariableName.get("T"); ParameterizedTypeName returnType = ParameterizedTypeName.get(ClassName.get(Updater.class), typeVariableName); ParameterSpec parameterSpec = ParameterSpec.builder( ParameterizedTypeName.get(ClassName.get(Class.class), typeVariableName), "tClass" ).build(); final String returnVariableName = "updater"; return MethodSpec.methodBuilder("getUpdater") .addAnnotation(AnnotationSpec.builder(SuppressWarnings.class) .addMember("value", "$S", "unchecked") .build()) .addModifiers(Modifier.PUBLIC) .addTypeVariable(typeVariableName) .addParameter(parameterSpec) .returns(returnType) .addStatement("$T $N = ($T)$N.get($N)", returnType, returnVariableName, returnType, mapField, parameterSpec) .beginControlFlow("if ($N == null)", returnVariableName) .addStatement("throw new $T(\"Updater for $N not found\")", RuntimeException.class, parameterSpec) .endControlFlow() .addStatement("return updater") .build(); }
private void generateMethod(TypeSpec.Builder classBuilder) { TypeVariableName t = TypeVariableName.get("T"); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(PocketBusConst.METHOD_GET_REGISTRAR) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addTypeVariable(t) .addParameter(t, PocketBusConst.VAR_TARGET) .returns(SubscriptionRegistration.class); boolean first = true; for (SubscriptionNode node : subscriptionTrees) { first = writeRegistrars(methodBuilder, node, first); } if (!first) { methodBuilder.endControlFlow(); } methodBuilder.addStatement("return null"); classBuilder.addMethod(methodBuilder.build()); }
/** * NOTE: the key of the returned map is of the raw type if the related * {@link NewDependencyInfo#getDependant()} is for a generic class. */ public static SetMultimap<NewBindingKey, NewDependencyInfo> collectionToMultimap( Collection<NewDependencyInfo> dependencies) { SetMultimap<NewBindingKey, NewDependencyInfo> result = HashMultimap.create(); for (NewDependencyInfo info : dependencies) { NewBindingKey key = info.getDependant(); TypeName typeName = key.getTypeName(); // For generic type with type variable, only keep raw type. if (typeName instanceof ParameterizedTypeName) { ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName; TypeName anyParameter = Preconditions.checkNotNull( Iterables.getFirst(parameterizedTypeName.typeArguments, null), String.format("ParameterizedTypeName of %s has no parameter.", key)); if (anyParameter instanceof TypeVariableName) { typeName = parameterizedTypeName.rawType; key = NewBindingKey.get(typeName, key.getQualifier()); } } result.put(key, info); } return result; }
/** * Adds the give {@link NewDependencyInfo} to the map, handling generic type with formal * parameters. Returns if it changed the given map. */ private boolean addDependencyInfo( SetMultimap<NewBindingKey, NewDependencyInfo> existingDependencies, NewDependencyInfo info) { NewBindingKey key = info.getDependant(); TypeName typeName = key.getTypeName(); // For generic type with type variable, only keep raw type. if (typeName instanceof ParameterizedTypeName) { ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName; TypeName anyParameter = Preconditions.checkNotNull( Iterables.getFirst(parameterizedTypeName.typeArguments, null), String.format("ParameterizedTypeName of %s has no parameter.", key)); if (anyParameter instanceof TypeVariableName) { typeName = parameterizedTypeName.rawType; key = NewBindingKey.get(typeName, key.getQualifier()); } } return existingDependencies.put(key, info); }
public static Map<TypeVariableName, TypeName> getMapFromTypeVariableToSpecialized( ParameterizedTypeName actual, ParameterizedTypeName formal) { Preconditions.checkArgument( formal.typeArguments.size() == actual.typeArguments.size(), String.format("Incompatible actual type %s and formal type %s.", actual, formal)); Preconditions.checkArgument( !formal.typeArguments.isEmpty(), String.format("formal type %s and actual type %s has no argument.", formal, actual)); Map<TypeVariableName, TypeName> result = new HashMap<>(); for (int i = 0; i < formal.typeArguments.size(); i++) { Preconditions.checkArgument( formal.typeArguments.get(i) instanceof TypeVariableName, String.format("formal type %s has non-TypeVariableName parameter.", formal)); Preconditions.checkArgument( !(actual.typeArguments.get(i) instanceof TypeVariableName), String.format("actual type %s has TypeVariableName parameter.", actual)); result.put(((TypeVariableName) formal.typeArguments.get(i)), actual.typeArguments.get(i)); } return result; }
/** * Returns a {@link TypeName} with all the {@link TypeVariableName} in the * given typeName replaced with the {@link TypeName} found in map the the * {@link TypeVariableName} if necessary. */ public static TypeName specializeIfNeeded( TypeName typeName, Map<TypeVariableName, TypeName> map) { if (typeName instanceof TypeVariableName) { Preconditions.checkArgument(map.containsKey(typeName)); return map.get(typeName); } else if (typeName instanceof ParameterizedTypeName) { ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName; ClassName rawName = parameterizedTypeName.rawType; List<TypeName> parameterTypes = new ArrayList<>(); for (TypeName t : parameterizedTypeName.typeArguments) { parameterTypes.add(specializeIfNeeded(t, map)); } return ParameterizedTypeName.get(rawName, parameterTypes.toArray(new TypeName[0])); } else { return typeName; } }
public static ColumnClassWriter from(@NonNull TransformerElement transformerElement, @NonNull Environment environment, boolean createUniqueClass) { final TypeName deserializedTypeName = transformerElement.getDeserializedTypeNameForGenerics(); final ClassName superClassName = transformerElement.isNumericType() ? NUMERIC_COLUMN : COLUMN; final TypeVariableName parentTableType = TypeVariableName.get("T"); final TypeVariableName nullabilityType = TypeVariableName.get("N"); final ExtendedTypeElement serializedType = transformerElement.getSerializedType(); final String className = createUniqueClass ? getUniqueClassName(transformerElement) : getClassName(transformerElement); return ColumnClassWriter.builder() .environment(environment) .className(className) .deserializedTypeName(deserializedTypeName) .serializedType(serializedType) .superClass(ParameterizedTypeName.get(superClassName, deserializedTypeName, deserializedTypeName, deserializedTypeName, parentTableType, nullabilityType)) .parentTableType(parentTableType) .nullabilityType(nullabilityType) .valueGetter(transformerElement.serializedValueGetter(VAL_VARIABLE)) .transformerElement(transformerElement) .nullable(!serializedType.isPrimitiveElement()) .unique(createUniqueClass) .build(); }
public static void addOperationByColumnToOperationBuilder(TypeSpec.Builder builder, TypeName interfaceName) { final TypeVariableName inputColumnType = TypeVariableName.get("C", ParameterizedTypeName.get(UNIQUE, NOT_NULLABLE_COLUMN)); builder .addField(FieldSpec .builder(OPERATION_BY_COLUMNS, OPERATION_BY_COLUMNS_VARIABLE, PRIVATE, FINAL) .addAnnotation(NON_NULL) .initializer("new $T<>(2)", ARRAY_LIST) .build()) .addMethod(MethodSpec .methodBuilder(METHOD_BY_COLUMN) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addAnnotation(NON_NULL) .addAnnotation(CHECK_RESULT) .addTypeVariable(inputColumnType) .addParameter(ParameterSpec.builder(inputColumnType, "column").build()) .returns(interfaceName) .addStatement("this.$L.add(($T) column)", OPERATION_BY_COLUMNS_VARIABLE, COLUMN) .addStatement("return this") .build()); }
@Override public MethodSpec methodSpec() { ParameterSpec handler = ParameterSpec.builder( ParameterizedTypeName.get(ClassName.get(Function.class), ClassName.get(Response.class), ClassName.bestGuess("T")), "handler").build(); return MethodSpec.methodBuilder(isNotEmpty(name) ? name : httpMethod) .addModifiers(Modifier.PUBLIC) .addTypeVariable(TypeVariableName.get("T")) .returns(ClassName.bestGuess("T")) .addJavadoc("$L\n", trimToEmpty(action.getDescription())) .addParameter(handler) .addStatement("return $L.apply($T.given().spec($L.build()).expect().spec($L.build()).when().$L($L))", handler.name, RestAssured.class, reqFieldName, respFieldName, httpMethod, uriConst ).build(); }
DtoGeneratorOutput.BuilderMethod builderMethod(SimpleRegularGoalDescription description, VarLife life) { ParameterSpec instance = parameterSpec(description.context.type, "instance"); List<List<TypeVariableName>> typeParams = life.typeParams(); MethodSpec.Builder builder = methodBuilder(description.details.name + "Builder") .addModifiers(description.details.access(STATIC)) .returns(parameterizedTypeName( contractType.nestedClass(upcase(description.parameters.get(0).name)), typeParams.get(0))); builder.addParameters( goalMethodParameters.apply(description.details, instance)); builder.addTypeVariables(typeParams.get(0)); builder.addCode(returnStatement.apply(description.details, instance)); return new DtoGeneratorOutput.BuilderMethod( description.details.name, builder.build()); }
private TypeSpec createStep(ImplFields implFields, List<List<TypeVariableName>> methodParams, List<List<TypeVariableName>> typeParams, int i) { ParameterSpec parameter = parameterSpec(description.parameters.get(i).type, description.parameters.get(i).name); List<FieldSpec> fields = implFields.fields.apply(description.details, i); TypeSpec.Builder builder = classBuilder(upcase(description.parameters.get(i).name)); builder.addMethod(createConstructor(fields)); return builder.addFields(fields) .addTypeVariables(typeParams.get(i)) .addMethod(methodBuilder(description.parameters.get(i).name) .addParameter(parameter) .addTypeVariables(methodParams.get(i)) .addModifiers(PUBLIC) .returns(nextStepType(description, typeParams, i)) .addCode(getCodeBlock(i, parameter)) .addExceptions(i == description.parameters.size() - 1 ? description.thrownTypes : emptyList()) .build()) .addModifiers(PUBLIC, STATIC, FINAL) .build(); }
private static boolean maybeTypevars(TypeName type) { if (!(type instanceof ParameterizedTypeName || type instanceof TypeVariableName)) { return false; } if (type instanceof ParameterizedTypeName) { for (TypeName targ : ((ParameterizedTypeName) type).typeArguments) { if (targ instanceof ParameterizedTypeName || targ instanceof TypeVariableName) { return true; } } return false; } return true; }
public static boolean references(TypeName type, TypeVariableName test) { if (!maybeTypevars(type)) { return false; } if (type instanceof TypeVariableName && ((TypeVariableName) type).bounds.isEmpty()) { return type.equals(test); } TypeWalk walk = new TypeWalk(type); while (walk.hasNext()) { if (walk.next().equals(test)) { return true; } } return false; }
public static List<TypeVariableName> extractTypeVars(TypeName type) { if (!maybeTypevars(type)) { return emptyList(); } List<TypeVariableName> builder = new ArrayList<>(); TypeWalk walk = new TypeWalk(type); while (walk.hasNext()) { TypeName next = walk.next(); if (next instanceof TypeVariableName) { if (!builder.contains(next)) { builder.add((TypeVariableName) next); } } } return builder; }
RequestBuilderGenerator(ProcessingEnvironment processingEnv, ProcessorUtil processorUtil) { this.processingEnv = processingEnv; this.processorUtil = processorUtil; requestBuilderType = processingEnv.getElementUtils() .getTypeElement(REQUEST_BUILDER_QUALIFIED_NAME); transcodeTypeName = TypeVariableName.get(TRANSCODE_TYPE_NAME); requestOptionsType = processingEnv.getElementUtils().getTypeElement( REQUEST_OPTIONS_QUALIFIED_NAME); }
@Override public JavaFile build() { TypeSpec.Builder result = TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC) .addTypeVariable(TypeVariableName.get("P", Presenter.class)) .superclass(ParameterizedTypeName.get(AndroidLoaderUtils.getLoader(supportLibrary), TypeVariableName.get("P"))); addConstructor(result); addFields(result); addMethods(result); return JavaFile.builder(getPackageName(), result.build()) .addFileComment("Generated class from EasyMVP. Do not modify!").build(); }
private void addFields(TypeSpec.Builder result) { result.addField(FieldSpec.builder(TypeVariableName.get("P"), FIELD_PRESENTER) .addModifiers(Modifier.PRIVATE) .build()); result.addField( FieldSpec.builder(PRESENTER_FACTORY_FIELD, FIELD_PRESENTER_FACTORY) .addModifiers(Modifier.PRIVATE) .build()); }
static MethodSpec.Builder overriding(ExecutableElement method) { String methodName = method.getSimpleName().toString(); MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName) .addAnnotation(Override.class); Set<Modifier> modifiers = method.getModifiers(); modifiers = new LinkedHashSet<>(modifiers); modifiers.remove(Modifier.ABSTRACT); Modifier defaultModifier = null; // Modifier.DEFAULT doesn't exist until Java 8. try { defaultModifier = Modifier.valueOf("DEFAULT"); } catch (IllegalArgumentException e) { // Ignored. } modifiers.remove(defaultModifier); builder = builder.addModifiers(modifiers); for (TypeParameterElement typeParameterElement : method.getTypeParameters()) { TypeVariable var = (TypeVariable) typeParameterElement.asType(); builder = builder.addTypeVariable(TypeVariableName.get(var)); } builder = builder.returns(TypeName.get(method.getReturnType())) .addParameters(getParameters(method)) .varargs(method.isVarArgs()); for (TypeMirror thrownType : method.getThrownTypes()) { builder = builder.addException(TypeName.get(thrownType)); } return builder; }
public TypeName getParameterizedParentTypeName() { if (parentUsedTypeParameters.size() > 0) { List<TypeName> usedParameters = new ArrayList<>(); for (String parameter : parentUsedTypeParameters) { if (parameter.indexOf(".") > 0) { usedParameters.add(ClassName.bestGuess(parameter)); } else { usedParameters.add(TypeVariableName.get(parameter)); } } return ParameterizedTypeName.get((ClassName)parentTypeName, usedParameters.toArray(new TypeName[usedParameters.size()])); } else { return parentTypeName; } }