Java Code Examples for com.squareup.javapoet.MethodSpec.Builder#build()
The following examples show how to use
com.squareup.javapoet.MethodSpec.Builder#build() .
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: ToStringMethod.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
static MethodSpec generate(TypeElement element) { ClassName.get(element).reflectionName(); Builder result = MethodSpec.methodBuilder("toString") .addModifiers(Modifier.PUBLIC) .returns(String.class) .addAnnotation(Override.class) .addCode( CodeBlock.builder() .add( "StringBuilder sb = new StringBuilder(\"@$L\");\n", ClassName.get(element).reflectionName().replace('$', '.')) .build()); List<ExecutableElement> methods = ElementFilter.methodsIn(element.getEnclosedElements()); if (!methods.isEmpty()) { result.addCode("sb.append('(');\n"); } for (ExecutableElement method : methods) { result.addCode("sb.append(\"$1L=\").append($1L);\n", method.getSimpleName()); } if (!methods.isEmpty()) { result.addCode("sb.append(')');\n"); } result.addCode("return sb.toString();\n"); return result.build(); }
Example 2
Source File: ValueTypeFactory.java From dataenum with Apache License 2.0 | 6 votes |
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(); }
Example 3
Source File: ResourceMethodExtensionPlugin.java From raml-module-builder with Apache License 2.0 | 6 votes |
private MethodSpec.Builder cloneMethodWithoutParams(Builder methodSpec){ MethodSpec spec = methodSpec.build(); MethodSpec.Builder newBuilder = MethodSpec.methodBuilder(methodSpec.build().name); newBuilder.addAnnotations(spec.annotations); newBuilder.addCode(spec.code); newBuilder.addExceptions(spec.exceptions); newBuilder.addTypeVariables(spec.typeVariables); newBuilder.addModifiers(spec.modifiers); newBuilder.returns(spec.returnType); if(spec.defaultValue != null){ newBuilder.defaultValue(spec.defaultValue); } newBuilder.varargs(spec.varargs); newBuilder.addCode(spec.javadoc); return newBuilder; }
Example 4
Source File: SensorAnnotationsFileBuilder.java From SensorAnnotations with Apache License 2.0 | 6 votes |
/** * Creates the implementation of {@code SensorEventListener#onSensorChanged(SensorEvent)} which * calls the annotated method on our target class. * * @param annotatedMethod Method annotated with {@code OnSensorChanged}. * @return {@link MethodSpec} of {@code SensorEventListener#onSensorChanged(SensorEvent)}. */ @NonNull private static MethodSpec createOnSensorChangedListenerMethod( @Nullable AnnotatedMethod annotatedMethod) { ParameterSpec sensorEventParameter = ParameterSpec.builder(SENSOR_EVENT, "event").build(); Builder methodBuilder = getBaseMethodBuilder("onSensorChanged").addParameter(sensorEventParameter); if (annotatedMethod != null) { ExecutableElement sensorChangedExecutableElement = annotatedMethod.getExecutableElement(); methodBuilder.addStatement("target.$L($N)", sensorChangedExecutableElement.getSimpleName(), sensorEventParameter); } return methodBuilder.build(); }
Example 5
Source File: SensorAnnotationsFileBuilder.java From SensorAnnotations with Apache License 2.0 | 6 votes |
/** * Creates the implementation of {@code SensorEventListener#onAccuracyChanged(Sensor, int)} * which calls the annotated method on our target class. * * @param annotatedMethod Method annotated with {@link OnAccuracyChanged}. * @return {@link MethodSpec} of {@code SensorEventListener#onAccuracyChanged(Sensor, int)}. */ @NonNull private static MethodSpec createOnAccuracyChangedListenerMethod( @Nullable AnnotatedMethod annotatedMethod) { ParameterSpec sensorParameter = ParameterSpec.builder(SENSOR, "sensor").build(); ParameterSpec accuracyParameter = ParameterSpec.builder(TypeName.INT, "accuracy").build(); Builder methodBuilder = getBaseMethodBuilder("onAccuracyChanged").addParameter(sensorParameter) .addParameter(accuracyParameter); if (annotatedMethod != null) { ExecutableElement accuracyChangedExecutableElement = annotatedMethod.getExecutableElement(); methodBuilder.addStatement("target.$L($N, $N)", accuracyChangedExecutableElement.getSimpleName(), sensorParameter, accuracyParameter); } return methodBuilder.build(); }
Example 6
Source File: ValueMethods.java From dataenum with Apache License 2.0 | 5 votes |
public MethodSpec createAsMethod(OutputSpec spec) { Builder builder = MethodSpec.methodBuilder("as" + value.name()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(value.parameterizedOutputClass()) .addStatement("return ($T) this", value.parameterizedOutputClass()); if (!ValueTypeFactory.extractMissingTypeVariablesForValue(value, spec).isEmpty() && value.hasTypeVariables()) { builder.addAnnotation(ValueTypeFactory.SUPPRESS_UNCHECKED_WARNINGS); } return builder.build(); }
Example 7
Source File: ResourceMethodExtensionPlugin.java From raml-module-builder with Apache License 2.0 | 4 votes |
private Builder generateOverrides(String path, String verb, Builder methodSpec){ //clone the method without the params as we will need to update params with new / updated //annotations and this cannot be done directly on the method as these lists are immutable //as java poet allows building code but not editing?? MethodSpec.Builder ret = cloneMethodWithoutParams(methodSpec); //pull out original params and their annotations from here MethodSpec spec = methodSpec.build(); //use this list to remove and then update params whose annotations need changing since //the param list on the method in java poet is immutable this is a workaround List<ParameterSpec> modifiedParams = new ArrayList<>( spec.parameters ); //check if url has a param / params associated with it that needs overriding Map<String,JsonObject> overrideEntry = overrideMap.row(path); if(overrideEntry != null){ //this endpoint was found in the config file and has an override associated with one of //its parameters List<ParameterSpec> paramSpec = spec.parameters; int []i = new int[]{0}; for (i[0] = 0; i[0] < paramSpec.size(); i[0]++) { //clone the parameter so we can update it ParameterSpec.Builder newParam = cloneSingleParamNoAnnotations(paramSpec.get(i[0])); List<AnnotationSpec> originalAnnotations = getAnnotationsAsModifiableList(paramSpec.get(i[0])); //remove the param, we need to rebuild it and then add it again modifiedParams.remove(i[0]); Set<Entry<String, JsonObject>> entries = overrideEntry.entrySet(); entries.forEach( entry -> { //iterate through the params of the generated function for this url + verb and look //for the parameter whose annotation we need to override JsonObject job = entry.getValue(); String type = job.getString("type"); Object value = job.getValue(ANNOTATION_VALUE); String paramName = job.getString("paramName"); if(verb.equalsIgnoreCase(job.getString("verb")) && paramName.equalsIgnoreCase(paramSpec.get(i[0]).name)){ //make sure the verb is aligned //we found the parameter that should be overridden, for the path, and for the verb //we cannot update the param, so we need to recreate it and then update the list //by removing the old and adding the recreated param //we need the original annotations so that we can add the ones that were not updated for(int j=0; j<originalAnnotations.size(); j++ ){ if(originalAnnotations.get(j).type.toString() != null && Enum2Annotation.getAnnotation(type).endsWith(originalAnnotations.get(j).type.toString())){ originalAnnotations.remove(j); break; } } try { AnnotationSpec aSpec = buildAnnotation(Class.forName(Enum2Annotation.getAnnotation(type)), value, type); originalAnnotations.add(aSpec); } catch (ClassNotFoundException e) { log.error(e.getMessage(), e); } } }); newParam.addAnnotations(originalAnnotations); modifiedParams.add(i[0], newParam.build()); } } ret.addParameters(modifiedParams); return ret; }
Example 8
Source File: SensorAnnotationsFileBuilder.java From SensorAnnotations with Apache License 2.0 | 4 votes |
/** * Create the constructor for our generated class. * * @param targetParameter The target class that has annotated methods. * @param itemsMap A map of sensor types found in the annotations with the annotated methods. * @return {@link MethodSpec} representing the constructor of our generated class. */ @NonNull private static MethodSpec createConstructor(@NonNull ParameterSpec targetParameter, @NonNull Map<Integer, Map<Class, AnnotatedMethod>> itemsMap) throws ProcessingException { ParameterSpec contextParameter = ParameterSpec.builder(CONTEXT, "context").build(); Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(contextParameter) .addParameter(targetParameter) .addStatement("this.$N = ($T) $N.getSystemService(SENSOR_SERVICE)", SENSOR_MANAGER_FIELD, SENSOR_MANAGER, contextParameter) .addStatement("this.$N = new $T()", LISTENER_WRAPPERS_FIELD, ARRAY_LIST); // Loop through the sensor types that we have annotations for and create the listeners which // will call the annotated methods on our target class. for (Integer sensorType : itemsMap.keySet()) { Map<Class, AnnotatedMethod> annotationMap = itemsMap.get(sensorType); AnnotatedMethod sensorChangedAnnotatedMethod = annotationMap.get(OnSensorChanged.class); AnnotatedMethod accuracyChangedAnnotatedMethod = annotationMap.get(OnAccuracyChanged.class); AnnotatedMethod triggerAnnotatedMethod = annotationMap.get(OnTrigger.class); if (sensorType == TYPE_SIGNIFICANT_MOTION && (accuracyChangedAnnotatedMethod != null || sensorChangedAnnotatedMethod != null)) { throw new ProcessingException(null, String.format( "@%s and @%s are not supported for the \"TYPE_SIGNIFICANT_MOTION\" type. Use @%s for this type.", OnSensorChanged.class.getSimpleName(), OnAccuracyChanged.class.getSimpleName(), OnTrigger.class.getSimpleName())); } else if (sensorType != TYPE_SIGNIFICANT_MOTION && triggerAnnotatedMethod != null) { throw new ProcessingException(null, String.format( "The @%s is only supported for the \"TYPE_SIGNIFICANT_MOTION\" type.", OnTrigger.class.getSimpleName())); } CodeBlock listenerWrapperCodeBlock; if (triggerAnnotatedMethod != null) { listenerWrapperCodeBlock = createTriggerListenerWrapper(triggerAnnotatedMethod); constructorBuilder.addCode(listenerWrapperCodeBlock); } else if (sensorChangedAnnotatedMethod != null || accuracyChangedAnnotatedMethod != null) { listenerWrapperCodeBlock = createSensorListenerWrapper(sensorType, sensorChangedAnnotatedMethod, accuracyChangedAnnotatedMethod); constructorBuilder.addCode(listenerWrapperCodeBlock); } } return constructorBuilder.build(); }