com.squareup.javapoet.ClassName Java Examples
The following examples show how to use
com.squareup.javapoet.ClassName.
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: JTypeName.java From gwt-jackson with Apache License 2.0 | 6 votes |
private ClassName className( JClassType type ) { JClassType enclosingType = type.getEnclosingType(); if ( null == enclosingType ) { return ClassName.get( type.getPackage() .getName(), type.getSimpleSourceName() ); } // We look for all enclosing types and add them at the head. List<String> types = new ArrayList<String>(); types.add( type.getSimpleSourceName() ); while ( null != enclosingType ) { types.add( 0, enclosingType.getSimpleSourceName() ); enclosingType = enclosingType.getEnclosingType(); } // The parent type is the first one. We remove it to keep only the childs. String parentType = types.remove( 0 ); String[] childs = types.toArray( new String[types.size()] ); return ClassName.get( type.getPackage() .getName(), parentType, childs ); }
Example #2
Source File: BeanJsonDeserializerCreator.java From gwt-jackson with Apache License 2.0 | 6 votes |
private List<MethodSpec> buildCommonPropertyDeserializerMethods( PropertyInfo property, JDeserializerType deserializerType ) throws UnableToCompleteException { List<MethodSpec> result = new ArrayList<MethodSpec>(); result.add( MethodSpec.methodBuilder( "newDeserializer" ) .addModifiers( Modifier.PROTECTED ) .addAnnotation( Override.class ) .returns( ParameterizedTypeName.get( ClassName.get( JsonDeserializer.class ), DEFAULT_WILDCARD ) ) .addStatement( "return $L", deserializerType.getInstance() ) .build() ); Optional<MethodSpec> paramMethod = buildPropertyDeserializerParameters( property, deserializerType ); if ( paramMethod.isPresent() ) { result.add( paramMethod.get() ); } return result; }
Example #3
Source File: GenClassesManagerWriter.java From sqlitemagic with Apache License 2.0 | 6 votes |
private CodeBlock buildViewSchemaCreations(GenClassesManagerStep managerStep) { final CodeBlock.Builder builder = CodeBlock.builder(); final List<ViewElement> allViewElements = managerStep.getAllViewElements(); if (!allViewElements.isEmpty()) { addDebugLogging(builder, "Creating views"); for (ViewElement viewElement : allViewElements) { final ClassName viewDao = EntityEnvironment.getGeneratedDaoClassName(viewElement); builder.addStatement("$T.createView(db, $T.$L, $S)", SQL_UTIL, viewDao, FIELD_VIEW_QUERY, viewElement.getViewName()); } } return builder.build(); }
Example #4
Source File: ModelProperty.java From kripton with Apache License 2.0 | 6 votes |
/** * Instantiates a new model property. * * @param entity the entity * @param element the element * @param modelAnnotations the model annotations */ @SuppressWarnings("rawtypes") public ModelProperty(ModelEntity<?> entity, Element element, List<ModelAnnotation> modelAnnotations) { super((element != null) ? element.getSimpleName().toString() : null, element); this.parent = new WeakReference<ModelEntity>(entity); if (element != null) { TypeName temp1=TypeName.get(element.asType()); LiteralType temp2 = LiteralType.of(element.asType().toString()); AssertKripton.fail((temp1 instanceof ClassName) && temp2.isCollection(), "In bean '%s' property '%s' can not use Object as parameter", entity.getElement().asType().toString() ,element.getSimpleName().toString()); propertyType = new ModelType(element.asType()); publicField = element.getModifiers().contains(Modifier.PUBLIC); } this.annotations = new ArrayList<ModelAnnotation>(); if (modelAnnotations != null) { this.annotations.addAll(modelAnnotations); } this.typeAdapter = new TypeAdapter(); }
Example #5
Source File: FinalRClassBuilder.java From Briefness with Apache License 2.0 | 6 votes |
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable, ClassName annotation) { String fieldName = variable.getNameAsString(); String fieldValue = variable.getInitializer() .map(Node::toString) .orElseThrow( () -> new IllegalStateException("Field " + fieldName + " missing initializer")); FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName) .addModifiers(PUBLIC, STATIC, FINAL) .initializer(fieldValue); if (annotation != null) { fieldSpecBuilder.addAnnotation(annotation); } resourceType.addField(fieldSpecBuilder.build()); }
Example #6
Source File: MethodExtractorUtils.java From litho with Apache License 2.0 | 6 votes |
private static List<AnnotationSpec> getExternalAnnotations(VariableElement param) { final List<? extends AnnotationMirror> annotationMirrors = param.getAnnotationMirrors(); final List<AnnotationSpec> annotations = new ArrayList<>(); for (AnnotationMirror annotationMirror : annotationMirrors) { if (annotationMirror.getAnnotationType().toString().startsWith(COMPONENTS_PACKAGE)) { continue; } final AnnotationSpec.Builder annotationSpec = AnnotationSpec.builder( ClassName.bestGuess(annotationMirror.getAnnotationType().toString())); Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = annotationMirror.getElementValues(); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> elementValue : elementValues.entrySet()) { annotationSpec.addMember( elementValue.getKey().getSimpleName().toString(), elementValue.getValue().toString()); } annotations.add(annotationSpec.build()); } return annotations; }
Example #7
Source File: NotNullValidatorTest.java From anno4j with Apache License 2.0 | 6 votes |
@Test public void addValueSpaceCheck() throws Exception { ParameterSpec paramS = ParameterSpec.builder(ClassName.get(String.class), "s") .build(); MethodSpec.Builder method = MethodSpec.methodBuilder("foo") .addModifiers(Modifier.PUBLIC) .addParameter(paramS) .returns(void.class); NotNullValidator validator = new NotNullValidator(); validator.addValueSpaceCheck(method, paramS, rdfsClazz); String code = method.build().code.toString(); Matcher matcher = Pattern.compile("if\\s*\\((s\\s*==\\s*null|null\\s*==\\s*s)\\)").matcher(code); assertTrue(matcher.find()); }
Example #8
Source File: BundlerClassInfo.java From easybundler with Apache License 2.0 | 6 votes |
public BundlerClassInfo(TypeElement te) { typeElement = te; className = ClassName.get(typeElement); for (Element e : te.getEnclosedElements()) { if (e.getKind() == ElementKind.FIELD) { VariableElement ve = (VariableElement) e; fields.add(ve); } if (e.getKind() == ElementKind.METHOD) { ExecutableElement ee = (ExecutableElement) e; methods.add(ee); } } }
Example #9
Source File: TypeNameMatcher.java From raml-java-tools with Apache License 2.0 | 6 votes |
public static Matcher<TypeName> typeName(final Matcher<? super ClassName> matcher) { final Matcher<? super ClassName> subMatcher = matcher; return new TypeSafeMatcher<TypeName>() { @Override protected boolean matchesSafely(TypeName item) { return subMatcher.matches(item); } @Override public void describeTo(Description description) { description.appendText("typename ").appendDescriptionOf(subMatcher); } }; }
Example #10
Source File: AsyncClientInterface.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Generate a simple method for operations with streaming input and output members. * Streaming input member takes a {@link Path} containing the data to upload and * the streaming output member takes a {@link Path} where data will be downloaded to. */ private MethodSpec streamingInputOutputFileSimpleMethod(OperationModel opModel) { ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); return interfaceMethodSignature(opModel) .returns(completableFutureType(getPojoResponseType(opModel))) .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.FILE)) .addParameter(requestType, opModel.getInput().getVariableName()) .addParameter(ClassName.get(Path.class), "sourcePath") .addParameter(ClassName.get(Path.class), "destinationPath") .addStatement("return $L($L, $T.fromFile(sourcePath), $T.toFile(destinationPath))", opModel.getMethodName(), opModel.getInput().getVariableName(), ClassName.get(AsyncRequestBody.class), ClassName.get(AsyncResponseTransformer.class)) .build(); }
Example #11
Source File: AutoMatterProcessor.java From auto-matter with Apache License 2.0 | 6 votes |
private MethodSpec optionalSetter(final Descriptor d, final ExecutableElement field) { String fieldName = fieldName(field); TypeName valueType = genericArgument(d, field, 0); ClassName optionalType = ClassName.bestGuess(optionalType(field)); TypeName parameterType = ParameterizedTypeName.get(optionalType, subtypeOf(valueType)); AnnotationSpec suppressUncheckedAnnotation = AnnotationSpec.builder(SuppressWarnings.class) .addMember("value", "$S", "unchecked") .build(); MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName) .addAnnotation(suppressUncheckedAnnotation) .addModifiers(PUBLIC) .addParameter(parameterType, fieldName) .returns(builderType(d)); if (shouldEnforceNonNull(field)) { assertNotNull(setter, fieldName); } setter.addStatement("this.$N = ($T)$N", fieldName, fieldType(d, field), fieldName); return setter.addStatement("return this").build(); }
Example #12
Source File: BindingClass.java From Aftermath with Apache License 2.0 | 6 votes |
private MethodSpec generateOnActivityResultMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("onActivityResult") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(void.class) .addParameter(TypeVariableName.get("T"), "target", Modifier.FINAL) .addParameter(int.class, "requestCode", Modifier.FINAL) .addParameter(int.class, "resultCode", Modifier.FINAL) .addParameter(ClassName.get("android.content", "Intent"), "data", Modifier.FINAL); final Map<Integer, MethodBinding> methodBindings = bindings.get(MethodBinding.onActivityResult); if (methodBindings != null && !methodBindings.isEmpty()) { boolean first = true; for (MethodBinding binding : methodBindings.values()) { if (first) { builder.beginControlFlow("if (requestCode == $L)", binding.requestCode); first = false; } else { builder.nextControlFlow("else if (requestCode == $L)", binding.requestCode); } builder.addStatement("target.$L(resultCode, data)", binding.name); } builder.endControlFlow(); } return builder.build(); }
Example #13
Source File: EnumerationTypeHandlerTest.java From raml-java-tools with Apache License 2.0 | 6 votes |
@Test public void createInteger() throws Exception { when(integerDeclaration.name()).thenReturn("Time"); when(integerDeclaration.enumValues()).thenReturn(Arrays.<Number>asList(1, 2, 3)); EnumerationTypeHandler handler = new EnumerationTypeHandler("time", integerDeclaration); GenerationContextImpl generationContext = new GenerationContextImpl(PluginManager.NULL, api, TypeFetchers.fromTypes(), "bar.pack", Collections.<String>emptyList()); generationContext.newExpectedType("Time", new CreationResult("bar.pack", ClassName.get("bar.pack", "Time"), null)); CreationResult result = handler.create(generationContext, new CreationResult("bar.pack", ClassName.get("bar.pack", "Time"), null)).get(); assertThat(result.getInterface(), allOf( name(equalTo("Time")), fields(Matchers.contains( FieldSpecMatchers.fieldName(equalTo("name")) ) ) )); System.err.println(result.getInterface().toString()); }
Example #14
Source File: BaseClientBuilderClass.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
private MethodSpec mergeServiceDefaultsMethod() { boolean crc32FromCompressedDataEnabled = model.getCustomizationConfig().isCalculateCrc32FromCompressedData(); MethodSpec.Builder builder = MethodSpec.methodBuilder("mergeServiceDefaults") .addAnnotation(Override.class) .addModifiers(PROTECTED, FINAL) .returns(SdkClientConfiguration.class) .addParameter(SdkClientConfiguration.class, "config") .addCode("return config.merge(c -> c.option($T.SIGNER, defaultSigner())\n", SdkAdvancedClientOption.class) .addCode(" .option($T" + ".CRC32_FROM_COMPRESSED_DATA_ENABLED, $L)", SdkClientOption.class, crc32FromCompressedDataEnabled); String clientConfigClassName = model.getCustomizationConfig().getServiceSpecificClientConfigClass(); if (StringUtils.isNotBlank(clientConfigClassName)) { builder.addCode(".option($T.SERVICE_CONFIGURATION, $T.builder().build())", SdkClientOption.class, ClassName.bestGuess(clientConfigClassName)); } builder.addCode(");"); return builder.build(); }
Example #15
Source File: InterceptorProcessor.java From EasyRouter with Apache License 2.0 | 6 votes |
private TypeSpec getInterceptorInitializer(Set<? extends Element> interceptorElements) throws ClassNotFoundException { ClassName interceptor = ClassName.get("com.android.easyrouter.intercept", "IInterceptor"); ClassName list = ClassName.get("java.util", "List"); TypeName interceptorList = ParameterizedTypeName.get(list, interceptor); MethodSpec.Builder routerInitBuilder = MethodSpec .methodBuilder("initModuleInterceptor") .returns(interceptorList) .addModifiers(Modifier.PUBLIC) .addModifiers(Modifier.STATIC); routerInitBuilder.addStatement("List<IInterceptor> list = new java.util.ArrayList()"); for (Element element : interceptorElements) { routerInitBuilder.addStatement("list.add(new $T())", ClassName.get((TypeElement) element)); } routerInitBuilder.addStatement("return list"); return TypeSpec.classBuilder(CompilerConstant.AutoCreateInterceptorPrefix + moduleName) .addModifiers(Modifier.PUBLIC) .addMethod(routerInitBuilder.build()) .build(); }
Example #16
Source File: ConstructorExtensionTest.java From raml-java-tools with Apache License 2.0 | 6 votes |
@Test public void simplest() throws Exception { Api api = RamlLoader.load(this.getClass().getResourceAsStream("simplest-type.raml"), "."); RamlToPojo ramlToPojo = new RamlToPojoBuilder(api).fetchTypes(TypeFetchers.fromAnywhere()).findTypes(TypeFinders.everyWhere()).build(Arrays.asList("core.constructor")); CreationResult r = ramlToPojo.buildPojos().creationResults().stream().filter(x -> x.getJavaName(EventType.INTERFACE).simpleName().equals("Foo")).findFirst().get(); assertThat(r.getInterface()).hasName("Foo"); System.err.println(r.getInterface().toString()); System.err.println(r.getImplementation().toString()); assertThat(r.getImplementation().get(), is(allOf( name(equalTo("FooImpl")), methods(containsInAnyOrder( allOf(methodName(equalTo("<init>"))), allOf(methodName(equalTo("<init>")), parameters(contains(type(equalTo(ClassName.get(String.class))), type(equalTo(ClassName.INT))))), allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class)))))), allOf(methodName(equalTo("getAge")), returnType(equalTo(ClassName.INT))), allOf(methodName(equalTo("setAge")), parameters(contains(type(equalTo(ClassName.INT))))) )) ))); }
Example #17
Source File: Generator.java From servicetalk with Apache License 2.0 | 5 votes |
private void addServiceInterfaces(final State state, final TypeSpec.Builder serviceClassBuilder) { TypeSpec interfaceSpec = newServiceInterfaceSpec(state, false); state.serviceClass = ClassName.bestGuess(interfaceSpec.name); serviceClassBuilder.addType(interfaceSpec); interfaceSpec = newServiceInterfaceSpec(state, true); state.blockingServiceClass = ClassName.bestGuess(interfaceSpec.name); serviceClassBuilder.addType(interfaceSpec); }
Example #18
Source File: PaperParcelWriter.java From paperparcel with Apache License 2.0 | 5 votes |
final TypeSpec.Builder write() { ClassName className = ClassName.get(descriptor.element()); return TypeSpec.classBuilder(name) .addModifiers(FINAL) .addFields(adapterDependencies(descriptor.adapters().values())) .addField(creator(className)) .addMethod(writeToParcel(className)) .addMethod(MethodSpec.constructorBuilder().addModifiers(PRIVATE).build()); }
Example #19
Source File: PoetGeneratorTaskIntegrationTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
private ClassSpec dummyClass() { return new ClassSpec() { @Override public TypeSpec poetSpec() { return TypeSpec.enumBuilder("Blah").addEnumConstant("FOO").addEnumConstant("BAR").build(); } @Override public ClassName className() { return ClassName.get(PACKAGE, "Blah"); } }; }
Example #20
Source File: TypeUtils.java From grouter-android with Apache License 2.0 | 5 votes |
public static TypeName getTypeName(String name) { switch (name) { case "void": return TypeName.VOID; case "int": return TypeName.get(int.class); case "int[]": return TypeName.get(int[].class); case "long": return TypeName.get(long.class); case "long[]": return TypeName.get(long[].class); case "double": return TypeName.get(double.class); case "double[]": return TypeName.get(double[].class); case "float": return TypeName.get(float.class); case "float[]": return TypeName.get(float[].class); case "boolean": return TypeName.get(boolean.class); case "boolean[]": return TypeName.get(boolean[].class); case "short": return TypeName.get(short.class); case "short[]": return TypeName.get(short[].class); case "char": return TypeName.get(char.class); case "char[]": return TypeName.get(char[].class); default: if (name.endsWith("[]")) { return ArrayTypeName.of(ClassName.bestGuess(name.substring(0, name.length() - 2))); } return ClassName.bestGuess(name); } }
Example #21
Source File: RegionGenerator.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
private MethodSpec regionsGetter() { return MethodSpec.methodBuilder("regions") .addModifiers(PUBLIC, STATIC) .returns(ParameterizedTypeName.get(ClassName.get(List.class), className())) .addStatement("return $L", "REGIONS") .build(); }
Example #22
Source File: SolidityFunctionWrapper.java From client-sdk-java with Apache License 2.0 | 5 votes |
static TypeName getNativeType(TypeName typeName) { if (typeName instanceof ParameterizedTypeName) { return getNativeType((ParameterizedTypeName) typeName); } String simpleName = ((ClassName) typeName).simpleName(); if (simpleName.equals(Address.class.getSimpleName())) { return TypeName.get(String.class); } else if (simpleName.startsWith("Uint")) { return TypeName.get(BigInteger.class); } else if (simpleName.startsWith("Int")) { return TypeName.get(BigInteger.class); } else if (simpleName.equals(Utf8String.class.getSimpleName())) { return TypeName.get(String.class); } else if (simpleName.startsWith("Bytes")) { return TypeName.get(byte[].class); } else if (simpleName.equals(DynamicBytes.class.getSimpleName())) { return TypeName.get(byte[].class); } else if (simpleName.equals(Bool.class.getSimpleName())) { return TypeName.get(Boolean.class); // boolean cannot be a parameterized type } else { throw new UnsupportedOperationException( "Unsupported type: " + typeName + ", no native type mapping exists."); } }
Example #23
Source File: AsyncClientClass.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
private MethodSpec constructor(Builder classBuilder) { MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .addParameter(SdkClientConfiguration.class, "clientConfiguration") .addStatement("this.clientHandler = new $T(clientConfiguration)", AwsAsyncClientHandler.class) .addStatement("this.clientConfiguration = clientConfiguration"); FieldSpec protocolFactoryField = protocolSpec.protocolFactory(model); if (model.getMetadata().isJsonProtocol()) { builder.addStatement("this.$N = init($T.builder()).build()", protocolFactoryField.name, protocolFactoryField.type); } else { builder.addStatement("this.$N = init()", protocolFactoryField.name); } if (model.getMetadata().isCborProtocol()) { builder.addStatement("this.jsonProtocolFactory = init($T.builder()).build()", AwsJsonProtocolFactory.class); } if (hasOperationWithEventStreamOutput()) { classBuilder.addField(FieldSpec.builder(ClassName.get(Executor.class), "executor", Modifier.PRIVATE, Modifier.FINAL) .build()); builder.addStatement("this.executor = clientConfiguration.option($T.FUTURE_COMPLETION_EXECUTOR)", SdkAdvancedAsyncClientOption.class); } if (model.getEndpointOperation().isPresent()) { builder.beginControlFlow("if (clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED))"); builder.addStatement("this.endpointDiscoveryCache = $T.create($T.create(this))", EndpointDiscoveryRefreshCache.class, poetExtensions.getClientClass(model.getNamingStrategy().getServiceName() + "AsyncEndpointDiscoveryCacheLoader")); builder.endControlFlow(); } return builder.build(); }
Example #24
Source File: RepackagePlugin.java From raml-java-tools with Apache License 2.0 | 5 votes |
private ClassName makeContained(String pack, ClassName currentSuggestion) { if ( currentSuggestion.simpleNames().size() > 1) { return ClassName.get(pack, currentSuggestion.simpleNames().get(0), currentSuggestion.simpleNames().subList(1, currentSuggestion.simpleNames().size()).toArray(new String[0])); } else { return ClassName.get(pack, currentSuggestion.simpleNames().get(0)); } }
Example #25
Source File: AutoValueRedactedExtension.java From auto-value-redacted with Apache License 2.0 | 5 votes |
@Override public String generateClass(Context context, String className, String classToExtend, boolean isFinal) { String packageName = context.packageName(); TypeElement autoValueClass = context.autoValueClass(); List<? extends TypeParameterElement> typeParameters = autoValueClass.getTypeParameters(); Name superName = autoValueClass.getSimpleName(); Map<String, ExecutableElement> properties = context.properties(); TypeSpec.Builder subclass = TypeSpec.classBuilder(className) // .addModifiers(isFinal ? Modifier.FINAL : Modifier.ABSTRACT) // .addMethod(generateConstructor(properties)) // .addMethod(generateToString(superName, properties)); ClassName superclass = ClassName.get(packageName, classToExtend); if (typeParameters.isEmpty()) { subclass.superclass(superclass); } else { List<TypeVariableName> typeVariables = new ArrayList<>(); for (TypeParameterElement typeParameter : typeParameters) { typeVariables.add(TypeVariableName.get(typeParameter)); } subclass.addTypeVariables(typeVariables) .superclass( ParameterizedTypeName.get(superclass, typeVariables.toArray(new TypeName[0]))); } JavaFile javaFile = JavaFile.builder(packageName, subclass.build()).build(); return javaFile.toString(); }
Example #26
Source File: BeanGetterHelper.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
private MethodSpec listOfBuildersGetter(MemberModel memberModel) { ClassName memberType = poetExtensions.getModelClass(memberModel.getListModel().getListMemberModel().getC2jShape()); TypeName returnType = ParameterizedTypeName.get(ClassName.get(Collection.class), memberType.nestedClass("Builder")); return basicGetter(memberModel, returnType, CodeBlock.builder().add( "return $1N != null ? $1N.stream().map($2T::toBuilder).collect($3T.toList()) : null", memberModel.getVariable().getVariableName(), memberType, Collectors.class) .build()); }
Example #27
Source File: LightCycleProcessor.java From lightcycle with Apache License 2.0 | 5 votes |
private void generateBinder(Set<String> erasedTargetNames, List<? extends Element> elements, Element hostElement) throws IOException { PackageElement packageElement = processingEnv.getElementUtils().getPackageOf(hostElement); final String simpleClassName = binderName(hostElement.getSimpleName().toString()); final String qualifiedClassName = packageElement.getQualifiedName() + "." + simpleClassName; JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile( qualifiedClassName, elements.toArray(new Element[elements.size()])); ClassName hostElementName = ClassName.bestGuess(hostElement.getSimpleName().toString()); MethodSpec bindMethod = MethodSpec.methodBuilder(METHOD_BIND_NAME) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(void.class) .addParameter(hostElementName, METHOD_BIND_ARGUMENT_NAME) .addCode(generateBindMethod(erasedTargetNames, hostElement, elements)) .build(); TypeSpec classType = TypeSpec.classBuilder(simpleClassName) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(bindMethod) .build(); final Writer writer = sourceFile.openWriter(); JavaFile.builder(packageElement.getQualifiedName().toString(), classType) .build() .writeTo(writer); writer.close(); }
Example #28
Source File: XSDValueSpaceValidator.java From anno4j with Apache License 2.0 | 5 votes |
private static void addNormalizedStringValidation(MethodSpec.Builder builder, ParameterSpec param) { TypeName string = ClassName.get(String.class); TypeName langString = ClassName.get(LangString.class); // Add check for Java's String type: builder.beginControlFlow("if($N instanceof $T)", param, string) .beginControlFlow("if((($T)$N).indexOf($S) != -1 || (($T)$N).indexOf($S) != -1 || (($T)$N).indexOf($S) != -1)", string, param, "\r", string, param, "\n", string, param, "\t") .addStatement("throw new $T($S)", ILLEGAL_ARG_EXCEPTION, "Value must be a normalized string. Must not contain carriage return, line feed or tab.") .endControlFlow() .endControlFlow(); // Add check for LangString: builder.beginControlFlow("else if($N instanceof $T)", param, langString) .beginControlFlow("if((($T)$N).indexOf($S) != -1 || (($T)$N).indexOf($S) != -1 || (($T)$N).indexOf($S) != -1)", langString, param, "\r", langString, param, "\n", langString, param, "\t") .addStatement("throw new $T($S)", ILLEGAL_ARG_EXCEPTION, "Value must be a normalized string. Must not contain carriage return, line feed or tab.") .endControlFlow() .endControlFlow(); // Throw exception if its neither String nor LangString: builder.beginControlFlow("else") .addStatement("throw new $T($S)", ILLEGAL_ARG_EXCEPTION, "Parameter type must either be String or LangString") .endControlFlow(); }
Example #29
Source File: AbiTypesMapperGenerator.java From client-sdk-java with Apache License 2.0 | 5 votes |
private void generate(String destinationDir) throws IOException { String typesPackageName = "org.web3j.abi.datatypes"; String autoGeneratedTypesPackageName = typesPackageName + ".generated"; MethodSpec.Builder builder = MethodSpec.methodBuilder("getType") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(String.class, TYPE) .returns( ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Object.class)) ) .beginControlFlow("switch (type)"); builder = addTypes(builder, typesPackageName); builder = addGeneratedTypes(builder, autoGeneratedTypesPackageName); builder = builder.addStatement("default:\nthrow new $T($S\n+ $N)", UnsupportedOperationException.class, "Unsupported type encountered: ", TYPE); builder.endControlFlow(); MethodSpec methodSpec = builder.build(); MethodSpec constructorSpec = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build(); TypeSpec typeSpec = TypeSpec .classBuilder("AbiTypes") .addJavadoc(buildWarning(AbiTypesMapperGenerator.class)) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(constructorSpec) .addMethod(methodSpec) .build(); write(autoGeneratedTypesPackageName, typeSpec, destinationDir); }
Example #30
Source File: AutoBundleWriter.java From AutoBundle with Apache License 2.0 | 5 votes |
private static MethodSpec createCallBuilderMethod(AutoBundleBindingClass target) { ClassName builderClass = getBuilderClassName(target); MethodSpec.Builder builder = MethodSpec.methodBuilder("builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addAnnotation(ANNOTATION_NONNULL) .returns(builderClass) .addCode("return new $T(", builderClass); for (int i = 0, count = target.getRequiredArgs().size(); i < count; i++) { AutoBundleBindingField arg = target.getRequiredArgs().get(i); ParameterSpec.Builder paramBuilder = ParameterSpec.builder(arg.getArgType(), arg.getArgKey()); // annotations if (arg.hasAnnotations()) { arg.getAnnotations().forEach(paramBuilder::addAnnotation); } // nonnull if (!arg.getArgType().isPrimitive()) { paramBuilder.addAnnotation(ANNOTATION_NONNULL); } // statement if (i > 0) { builder.addCode(", "); } builder.addParameter(paramBuilder.build()) .addCode("$N", arg.getArgKey()); } return builder.addCode(");\n").build(); }