private MethodSpec getSingletonSetterMethod(ClassName className, FieldSpec singletonField) { ParameterSpec parameter = ParameterSpec .builder(className, "wrapper") .build(); AnnotationSpec visibleForTesting = AnnotationSpec .builder(VisibleForTesting.class) .addMember("otherwise", "VisibleForTesting.NONE") .build(); return MethodSpec .methodBuilder("setInstance") .addAnnotation(visibleForTesting) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(parameter) .addStatement("$N = $N", singletonField, parameter) .build(); }
@Nonnull private MethodSpec buildContainsMethod( final TypeElement element, final ClassName arezType ) { final MethodSpec.Builder method = MethodSpec.methodBuilder( "contains" ). addModifiers( Modifier.PUBLIC ). addParameter( ParameterSpec.builder( TypeName.get( element.asType() ), "entity", Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ). returns( TypeName.BOOLEAN ); method.addStatement( "$N().reportObserved()", GET_OBSERVABLE_METHOD ); if ( null != _componentId ) { method.addStatement( "return this.$N.containsKey( entity.$N() )", ENTITIES_FIELD_NAME, getIdMethodName() ); } else { method.addStatement( "return entity instanceof $T && this.$N.containsKey( (($T) entity).$N() )", arezType, ENTITIES_FIELD_NAME, arezType, getIdMethodName() ); } return method.build(); }
private static MethodSpec getMethod(ClassName name, Key key) { Class<?> type = parseTypeFormat(key.getType(), key.getFormat()); if(type.isPrimitive()) { type = ClassUtils.primitiveToWrapper(type); } ParameterSpec parameter = ParameterSpec.builder(type, key.getId()).build(); return MethodSpec.methodBuilder(key.getId()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(parameter) .addStatement("this.$N = $N", key.getId(), parameter) .addJavadoc(key.getDescription()) .returns(name) .addStatement("return this") .build(); }
public static JavaFile logger(Domain ontology) { ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + LOGGER); ClassName statementName = ClassName.get(ontology.getTargetPackage(), ontology.getName() + STATEMENT); ParameterSpec loggerParameter = ParameterSpec.builder(org.slf4j.Logger.class, "logger").build(); return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name) .superclass(ParameterizedTypeName.get(ClassName.get(AbstractDomainLogger.class), statementName)) .addJavadoc(composeJavadoc(ontology, name)) .addModifiers(Modifier.PUBLIC) .addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(loggerParameter) .addStatement("super($N)", loggerParameter) .build()) .addMethod(getCreateLogStatementMethod(statementName)).build()).build(); }
@Nonnull private static MethodSpec.Builder buildStaticEventHandlerMethod( @Nonnull final ComponentDescriptor descriptor, @Nonnull final EventHandlerDescriptor eventHandler ) { final TypeName handlerType = TypeName.get( eventHandler.getEventHandlerType().asType() ); final String handlerName = "_" + eventHandler.getMethod().getSimpleName(); final MethodSpec.Builder method = MethodSpec.methodBuilder( handlerName ). addAnnotation( NONNULL_CLASSNAME ). returns( handlerType ); method.addModifiers( Modifier.STATIC ); final ParameterSpec.Builder parameter = ParameterSpec.builder( TypeName.get( descriptor.getElement().asType() ), "component", Modifier.FINAL ). addAnnotation( NONNULL_CLASSNAME ); method.addParameter( parameter.build() ); method.addStatement( "return (($T) component).$N", descriptor.getEnhancedClassName(), handlerName ); return method; }
@Nonnull private MethodSpec buildResultWrapperMethod() { final ParameterizedTypeName listType = ParameterizedTypeName.get( ClassName.get( List.class ), TypeName.get( getElement().asType() ) ); return MethodSpec.methodBuilder( "wrap" ). addModifiers( Modifier.PROTECTED, Modifier.FINAL ). addJavadoc( "If config option enabled, wrap the specified list in an immutable list and return it.\n" + "This method should be called by repository extensions when returning list results " + "when not using {@link #toList(List)}.\n" ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addParameter( ParameterSpec.builder( listType, "list", Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ). returns( listType ). addStatement( "return $T.areRepositoryResultsModifiable() ? $T.unmodifiableList( list ) : list", GeneratorUtil.AREZ_CLASSNAME, Collections.class ). build(); }
@Nonnull private MethodSpec buildGetByIdMethod() { final TypeName entityType = TypeName.get( getElement().asType() ); return MethodSpec.methodBuilder( "getBy" + getIdName() ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addParameter( ParameterSpec.builder( getIdType(), "id", Modifier.FINAL ).build() ). returns( entityType ). addStatement( "final $T entity = $N( id )", entityType, "findBy" + getIdName() ). addCode( CodeBlock.builder(). beginControlFlow( "if ( null == entity )" ). addStatement( "throw new $T( $T.class, id )", GeneratorUtil.NO_SUCH_ENTITY_EXCEPTION_CLASSNAME, entityType ). endControlFlow(). build() ). addStatement( "return entity" ). build(); }
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; }
@Nonnull @Override protected List<MethodSpec> buildMethods() { final MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC); final ImmutableList.Builder<MethodSpec> builder = ImmutableList.builder(); getProperties().entrySet().forEach(property -> { final String name = property.getKey(); final TypeName type = property.getValue(); final String fieldName = fieldNamePolicy.convert(name, type); final String methodName = methodNamePolicy.convert(name, type); builder.add(MethodSpec.methodBuilder(methodName) .addModifiers(Modifier.PUBLIC) .returns(type) .addStatement("return $L", fieldName) .build()); final String propertyName = parameterNamePolicy.convert(name, type); constructorBuilder.addParameter(ParameterSpec.builder(type, propertyName) .build()) .addStatement("this.$L = $L", fieldName, propertyName); }); builder.add(constructorBuilder.build()); return builder.build(); }
private MethodSpec generateUnboxMethod( ClassName className, TypeName typeName, String primitiveType) { String paramName = className.simpleName() + "Param"; paramName = Character.toLowerCase(paramName.charAt(0)) + paramName.substring(1); String primitiveArray = primitiveType + "s"; return MethodSpec.methodBuilder("toPrimitive") .addParameters(ImmutableList.of(ParameterSpec.builder(ArrayTypeName.of(className), paramName).build())) .returns(ArrayTypeName.of(typeName)) .addModifiers(PUBLIC) .addModifiers(STATIC) .addStatement("$L[] $L = new $L[$L.length]", primitiveType, primitiveArray, primitiveType, paramName) .beginControlFlow("for (int i = 0; i < $L.length; i++)", paramName) .addStatement("$L[i] = $L[i]", primitiveArray, paramName) .endControlFlow() .addStatement("return $L", primitiveArray) .build(); }
private void processInjector(PreferenceComponentAnnotatedClass annotatedClass) throws VerifyException { try { annotatedClass.annotatedElement.getEnclosedElements().stream() .filter(element -> element instanceof ExecutableElement) .map(element -> (ExecutableElement) element) .forEach(method -> { MethodSpec methodSpec = MethodSpec.overriding(method).build(); ParameterSpec parameterSpec = methodSpec.parameters.get(0); TypeElement injectedElement = processingEnv.getElementUtils().getTypeElement(parameterSpec.type.toString()); generateProcessInjector(annotatedClass, injectedElement); }); } catch (VerifyException e) { showErrorLog(e.getMessage(), annotatedClass.annotatedElement); e.printStackTrace(); } }
@Nonnull private MethodSpec buildFindAllByQuerySortedMethod() { final ParameterizedTypeName queryType = ParameterizedTypeName.get( ClassName.get( Predicate.class ), TypeName.get( getElement().asType() ) ); final ParameterizedTypeName sorterType = ParameterizedTypeName.get( ClassName.get( Comparator.class ), TypeName.get( getElement().asType() ) ); return MethodSpec.methodBuilder( "findAllByQuery" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addParameter( ParameterSpec.builder( queryType, "query", Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ). addParameter( ParameterSpec.builder( sorterType, "sorter", Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ). returns( ParameterizedTypeName.get( ClassName.get( List.class ), TypeName.get( getElement().asType() ) ) ). addStatement( "return toList( entities().stream().filter( query ).sorted( sorter ) )", Collectors.class ). build(); }
@Override public void decorateClass(TypeSpec.Builder toAddTo) { if (needsClassDecoration) { ParameterSpec param = ParameterSpec.builder(String.class, "code").build(); ClassName shell = ClassName.get("groovy.lang", "GroovyShell"); MethodSpec.Builder specBuilder = MethodSpec.methodBuilder(EXEC_NAME) .addModifiers(Modifier.PRIVATE) .addParameter(param) .returns(Object.class) .addCode("StringBuilder script = new StringBuilder();\n") .addCode("script.append($S);\n", "import "+packageName+".*\n") .addCode("script.append($N);\n", param) .addCode("return new $L().evaluate(script.toString());\n", shell); toAddTo.addMethod(specBuilder.build()); } }
@Nonnull private MethodSpec buildGetByQueryMethod() { final TypeName entityType = TypeName.get( getElement().asType() ); final ParameterizedTypeName queryType = ParameterizedTypeName.get( ClassName.get( Predicate.class ), entityType ); return MethodSpec.methodBuilder( "getByQuery" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addParameter( ParameterSpec.builder( queryType, "query", Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ). returns( entityType ). addStatement( "final $T entity = findByQuery( query )", entityType ). addCode( CodeBlock.builder(). beginControlFlow( "if ( null == entity )" ). addStatement( "throw new $T()", GeneratorUtil.NO_RESULT_EXCEPTION_CLASSNAME ). endControlFlow(). build() ). addStatement( "return entity" ). build(); }
protected ParameterSpec memberAsBeanStyleParameter() { if (memberModel.hasBuilder()) { TypeName builderName = poetExtensions.getModelClass(memberModel.getC2jShape()).nestedClass("BuilderImpl"); return ParameterSpec.builder(builderName, fieldName()).build(); } if (memberModel.isList() && hasBuilder(memberModel.getListModel().getListMemberModel())) { TypeName memberName = poetExtensions.getModelClass(memberModel.getListModel().getListMemberModel().getC2jShape()) .nestedClass("BuilderImpl"); TypeName listType = ParameterizedTypeName.get(ClassName.get(Collection.class), memberName); return ParameterSpec.builder(listType, fieldName()).build(); } if (memberModel.isMap() && hasBuilder(memberModel.getMapModel().getValueModel())) { TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel() .getVariable().getVariableType()); TypeName valueType = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape()) .nestedClass("BuilderImpl"); TypeName mapType = ParameterizedTypeName.get(ClassName.get(Map.class), keyType, valueType); return ParameterSpec.builder(mapType, fieldName()).build(); } return memberAsParameter(); }
@Nonnull private MethodSpec buildListConverterMethod() { final ParameterizedTypeName streamType = ParameterizedTypeName.get( ClassName.get( Stream.class ), TypeName.get( getElement().asType() ) ); return MethodSpec.methodBuilder( "toList" ). addModifiers( Modifier.PROTECTED, Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addJavadoc( "Convert specified stream to a list, wrapping as an immutable list if required.\n" + "This method should be called by repository extensions when returning list results.\n" ). addParameter( ParameterSpec.builder( streamType, "stream", Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ). returns( ParameterizedTypeName.get( ClassName.get( List.class ), TypeName.get( getElement().asType() ) ) ). addStatement( "return wrap( stream.collect( $T.toList() ) )", Collectors.class ). build(); }
public static CodeBlock writeValueWithTypeAdapter(FieldSpec adapter, AutoMappperProcessor.Property p, ParameterSpec out) { CodeBlock.Builder block = CodeBlock.builder(); if (p.isNullable()) { block.beginControlFlow("if ($N == null)", p.fieldName); block.addStatement("$N.writeInt(1)", out); block.nextControlFlow("else"); block.addStatement("$N.writeInt(0)", out); } block.addStatement("$N.toParcel($N, $N)", adapter, p.fieldName, out); if (p.isNullable()) { block.endControlFlow(); } return block.build(); }
public static MethodSpec constructorGroupMethod() { ClassName className = ClassName.get("com.kii.cloud.storage", "KiiGroup"); ParameterSpec parameterSpec = ParameterSpec.builder(className, "kiiGroup").build(); return MethodSpec .constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(parameterSpec) .addStatement("this.kiiGroup = kiiGroup") .build(); }
@TargetApi(24) private List<MethodSpec> getConstructorSpecs(List<ExecutableElement> constructorElements, TypeElement originalClass) { return constructorElements.stream() .map(constructor -> { List<String> parameterNames = constructor.getParameters() .stream() .map(parameter -> parameter.getSimpleName().toString()) .collect(Collectors.toList()); List<ParameterSpec> parameters = constructor.getParameters() .stream() .map(ParameterSpec::get) .collect(Collectors.toList()); MethodSpec.Builder constructorBuilder = MethodSpec .constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameters(parameters) .addStatement("super($L)", String.join(",", parameterNames)); MethodSpec.Builder initializerBuilder = MethodSpec .methodBuilder("newInstance") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(TypeName.get(originalClass.asType())) .addParameters(parameters) .addStatement("return new $L($L)", getSubclassName(originalClass), String.join(",", parameterNames)); return Arrays.asList(constructorBuilder.build(), initializerBuilder.build()); }) .flatMap(Collection::stream) .collect(Collectors.toList()); }
CodeBlock generateSeeMethodJavadoc( TypeName nameOfClassContainingMethod, MethodSpec methodSpec) { return generateSeeMethodJavadocInternal(nameOfClassContainingMethod, methodSpec.name, Lists.transform(methodSpec.parameters, new Function<ParameterSpec, Object>() { @Override public Object apply(ParameterSpec input) { return input.type; } })); }
/** * The {@link com.bumptech.glide.request.RequestOptions} subclass should always be our * generated subclass type to avoid inadvertent errors where a different subclass is applied that * accidentally wipes out some logic in overidden methods in our generated subclass. */ @Nullable private MethodSpec generateOverrideSetRequestOptions( String generatedCodePackageName, @Nullable TypeSpec generatedRequestOptions) { if (generatedRequestOptions == null) { return null; } Elements elementUtils = processingEnv.getElementUtils(); TypeElement requestOptionsType = elementUtils.getTypeElement( RequestOptionsGenerator.REQUEST_OPTIONS_QUALIFIED_NAME); TypeElement androidNonNullType = elementUtils.getTypeElement("android.support.annotation.NonNull"); // This class may have just been generated and therefore may not be found if we try to obtain // it via Elements, so use just the String version instead. String generatedRequestOptionsQualifiedName = generatedCodePackageName + "." + generatedRequestOptions.name; String methodName = "setRequestOptions"; String parameterName = "toSet"; return MethodSpec.methodBuilder(methodName) .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .addParameter( ParameterSpec.builder(ClassName.get(requestOptionsType), parameterName) .addAnnotation(ClassName.get(androidNonNullType)) .build()) .beginControlFlow("if ($N instanceof $L)", parameterName, generatedRequestOptionsQualifiedName) .addStatement("super.$N($N)", methodName, parameterName) .nextControlFlow("else") .addStatement("super.setRequestOptions(new $L().apply($N))", generatedRequestOptionsQualifiedName, parameterName) .endControlFlow() .build(); }
MethodSignature(MethodSpec spec) { name = spec.name; modifiers = spec.modifiers; returnType = spec.returnType; parameterTypes = Lists.transform(spec.parameters, new Function<ParameterSpec, TypeName>() { @Nullable @Override public TypeName apply(ParameterSpec parameterSpec) { return parameterSpec.type; } }); }
/** * Generates a particular method with an equivalent name and arguments to the given method * from the generated {@link com.bumptech.glide.request.BaseRequestBuilder} subclass. */ private MethodSpec generateGeneratedRequestOptionEquivalent(MethodSpec requestOptionMethod) { CodeBlock callRequestOptionsMethod = CodeBlock.builder() .add(".$N(", requestOptionMethod.name) .add(FluentIterable.from(requestOptionMethod.parameters) .transform(new Function<ParameterSpec, String>() { @Override public String apply(ParameterSpec input) { return input.name; } }) .join(Joiner.on(", "))) .add(");\n") .build(); return MethodSpec.methodBuilder(requestOptionMethod.name) .addJavadoc( processorUtil.generateSeeMethodJavadoc(requestOptionsClassName, requestOptionMethod)) .addModifiers(Modifier.PUBLIC) .addTypeVariables(requestOptionMethod.typeVariables) .addParameters(requestOptionMethod.parameters) .returns(generatedRequestBuilderOfTranscodeType) .beginControlFlow( "if (getMutableOptions() instanceof $T)", requestOptionsClassName) .addCode("this.requestOptions = (($T) getMutableOptions())", requestOptionsClassName) .addCode(callRequestOptionsMethod) .nextControlFlow("else") .addCode(CodeBlock.of("this.requestOptions = new $T().apply(this.requestOptions)", requestOptionsClassName)) .addCode(callRequestOptionsMethod) .endControlFlow() .addStatement("return this") .build(); }
@Nonnull private MethodSpec buildFindAllSortedMethod() { final ParameterizedTypeName sorterType = ParameterizedTypeName.get( ClassName.get( Comparator.class ), TypeName.get( getElement().asType() ) ); return MethodSpec.methodBuilder( "findAll" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addParameter( ParameterSpec.builder( sorterType, "sorter", Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ). returns( ParameterizedTypeName.get( ClassName.get( List.class ), TypeName.get( getElement().asType() ) ) ). addStatement( "return toList( entities().stream().sorted( sorter ) )", Collectors.class ). build(); }
static List<ParameterSpec> getParameters(List<? extends VariableElement> parameters) { List<ParameterSpec> result = new ArrayList<>(); for (VariableElement parameter : parameters) { result.add(getParameter(parameter)); } return result; }
@Nonnull private MethodSpec buildFindByQueryMethod() { final ParameterizedTypeName queryType = ParameterizedTypeName.get( ClassName.get( Predicate.class ), TypeName.get( getElement().asType() ) ); return MethodSpec.methodBuilder( "findByQuery" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME ). addParameter( ParameterSpec.builder( queryType, "query", Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ). returns( TypeName.get( getElement().asType() ) ). addStatement( "return entities().stream().filter( query ).findFirst().orElse( null )", Collectors.class ). build(); }
/** * The {@code RequestOptions} subclass should always be our * generated subclass type to avoid inadvertent errors where a different subclass is applied that * accidentally wipes out some logic in overidden methods in our generated subclass. */ @Nullable private MethodSpec generateOverrideSetRequestOptions( String generatedCodePackageName, @Nullable TypeSpec generatedRequestOptions) { if (generatedRequestOptions == null) { return null; } Elements elementUtils = processingEnv.getElementUtils(); TypeElement requestOptionsType = elementUtils.getTypeElement( RequestOptionsGenerator.REQUEST_OPTIONS_QUALIFIED_NAME); TypeElement androidNonNullType = elementUtils.getTypeElement("android.support.annotation.NonNull"); // This class may have just been generated and therefore may not be found if we try to obtain // it via Elements, so use just the String version instead. String generatedRequestOptionsQualifiedName = generatedCodePackageName + "." + generatedRequestOptions.name; String methodName = "setRequestOptions"; String parameterName = "toSet"; return MethodSpec.methodBuilder(methodName) .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .addParameter( ParameterSpec.builder(ClassName.get(requestOptionsType), parameterName) .addAnnotation(ClassName.get(androidNonNullType)) .build()) .beginControlFlow("if ($N instanceof $L)", parameterName, generatedRequestOptionsQualifiedName) .addStatement("super.$N($N)", methodName, parameterName) .nextControlFlow("else") .addStatement("super.setRequestOptions(new $L().apply($N))", generatedRequestOptionsQualifiedName, parameterName) .endControlFlow() .build(); }
MethodSignature(MethodSpec spec) { name = spec.name; isStatic = spec.modifiers.contains(Modifier.STATIC); returnType = spec.returnType; parameterTypes = Lists.transform(spec.parameters, new Function<ParameterSpec, TypeName>() { @Nullable @Override public TypeName apply(ParameterSpec parameterSpec) { return parameterSpec.type; } }); }
public static <Q extends TypeName> Matcher<ParameterSpec> type(Matcher<Q> match) { return new FeatureMatcher<ParameterSpec, Q>(match, "type name", "type name") { @Override protected Q featureValueOf(ParameterSpec actual) { return (Q) actual.type; } }; }
public static Matcher<MethodSpec> parameters(Matcher<Iterable<? extends ParameterSpec>> memberMatcher) { return new FeatureMatcher<MethodSpec, Iterable<? extends ParameterSpec>>(memberMatcher, "parameter", "parameter") { @Override protected Iterable<? extends ParameterSpec> featureValueOf(MethodSpec actual) { return actual.parameters; } }; }
/** Compose method parameters that mimic original code. */ @NonNull public static StringBuilder mimicParameters(@NonNull final MethodSpec.Builder builder, @NonNull final Symbol.MethodSymbol ms) throws Exception { String delimiter = ""; final StringBuilder arguments = new StringBuilder(); final com.sun.tools.javac.util.List<Symbol.VarSymbol> parameters = ms.getParameters(); for (int i = 0, len = parameters.size(); i < len; i++) { final Symbol.VarSymbol param = parameters.get(i); // mimic parameter of the method: name, type, modifiers final TypeName paramType = TypeName.get(param.asType()); final String parameterName = param.name.toString(); final ParameterSpec.Builder parameter = ParameterSpec.builder(paramType, parameterName, Modifier.FINAL); if (param.hasAnnotations()) { // DONE: copy annotations of parameter for (final Attribute.Compound am : param.getAnnotationMirrors()) { final AnnotationSpec.Builder builderAnnotation = mimicAnnotation(am); if (null != builderAnnotation) { parameter.addAnnotation(builderAnnotation.build()); } } } // support VarArgs if needed builder.varargs(ms.isVarArgs() && i == len - 1); builder.addParameter(parameter.build()); // compose parameters list for forwarding arguments.append(delimiter).append(parameterName); delimiter = ", "; } return arguments; }
/** * * @param field * @param namingConvention * @param returnObject * @return */ public static MethodSpec.Builder forField(FieldSpec field, String namingConvention, ParameterSpec returnObject) { MethodSpec.Builder builder = MethodSpec.methodBuilder(makeName(namingConvention, field.name)) .addJavadoc(field.javadoc) .addParameter(field.type, field.name) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addStatement("this.$N = $N", field.name, field.name); if (returnObject != null) { builder.returns(returnObject.type) .addStatement("return $N", returnObject.name); } return builder; }
public static JavaFile markerBuilder(Domain ontology) { List<Key> keys = ontology.getKeys(); ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName()+ MARKER_BUILDER); Builder builder = TypeSpec.classBuilder(name) .addJavadoc(composeJavadoc(ontology, name)) .addModifiers(Modifier.PUBLIC); ClassName markerName = getName(ontology); for(Key key : keys) { builder.addMethod(getBuilderMethod(markerName, key)); } if(ontology.hasTags()) { ClassName tagsName = TagGenerator.getName(ontology); ParameterSpec parameter = ParameterSpec.builder(ArrayTypeName.of(tagsName), "value").build(); builder.addMethod(MethodSpec.methodBuilder("tags") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(parameter).varargs() .addStatement("$T marker = new $T()", markerName, markerName) .addStatement("marker.tags($N)", parameter) .returns(markerName) .addStatement("return marker") .build()); } return JavaFile.builder(name.packageName(), builder.build()).build(); }
private static MethodSpec getBuilderMethod(ClassName name, Key key) { Class<?> type = parseTypeFormat(key.getType(), key.getFormat()); ParameterSpec parameter = ParameterSpec.builder(type, "value").build(); return MethodSpec.methodBuilder(key.getId()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(parameter) .addStatement("$T marker = new $T()", name, name) .addStatement("marker." + key.getId() + "($N)", parameter) .addJavadoc(key.getDescription()) .returns(name) .addStatement("return marker") .build(); }
private static MethodSpec getMethod(ClassName name, Key key) { Class<?> type = parseTypeFormat(key.getType(), key.getFormat()); ParameterSpec parameter = ParameterSpec.builder(type, "value").build(); return MethodSpec.methodBuilder(key.getId()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(parameter) .addStatement("marker." + key.getId() + "($N)", parameter) .addJavadoc(key.getDescription()).returns(name) .addStatement("return this") .build(); }
static void copyDocumentedAnnotations( @Nonnull final AnnotatedConstruct element, @Nonnull final ParameterSpec.Builder builder ) { for ( final AnnotationMirror annotation : element.getAnnotationMirrors() ) { if ( null != annotation.getAnnotationType().asElement().getAnnotation( Documented.class ) ) { builder.addAnnotation( AnnotationSpec.get( annotation ) ); } } }
@Nonnull private static MethodSpec.Builder buildEventHandlerActionMethod( @Nonnull final EventHandlerDescriptor eventHandler ) { final MethodSpec.Builder method = MethodSpec.methodBuilder( eventHandler.getMethod().getSimpleName().toString() ). returns( TypeName.get( eventHandler.getMethodType().getReturnType() ) ); ProcessorUtil.copyTypeParameters( eventHandler.getMethodType(), method ); ProcessorUtil.copyAccessModifiers( eventHandler.getMethod(), method ); ProcessorUtil.copyDocumentedAnnotations( eventHandler.getMethod(), method ); final AnnotationSpec.Builder annotation = AnnotationSpec.builder( ACTION_CLASSNAME ). addMember( "reportParameters", "false" ); method.addAnnotation( annotation.build() ); final int paramCount = eventHandler.getMethod().getParameters().size(); for ( int i = 0; i < paramCount; i++ ) { final TypeMirror paramType = eventHandler.getMethodType().getParameterTypes().get( i ); final ParameterSpec.Builder parameter = ParameterSpec.builder( TypeName.get( paramType ), "arg" + i, Modifier.FINAL ); ProcessorUtil.copyDocumentedAnnotations( eventHandler.getMethod().getParameters().get( i ), parameter ); method.addParameter( parameter.build() ); } final String params = 0 == paramCount ? "" : IntStream.range( 0, paramCount ).mapToObj( i -> "arg" + i ).collect( Collectors.joining( "," ) ); final boolean isVoid = eventHandler.getMethodType().getReturnType().getKind() == TypeKind.VOID; method.addStatement( ( isVoid ? "" : "return " ) + "super.$N(" + params + ")", eventHandler.getMethod().getSimpleName() ); return method; }