Java Code Examples for com.squareup.javapoet.MethodSpec#methodBuilder()
The following examples show how to use
com.squareup.javapoet.MethodSpec#methodBuilder() .
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: ArgumentBuildersModel.java From Akatsuki with Apache License 2.0 | 6 votes |
private MethodSpec.Builder createBuilderMethod(ArgumentBuilderModel model, TypeSpec builderSpec, boolean withBundle) { MethodSpec.Builder builder = MethodSpec.methodBuilder(model.classModel().simpleName()); if (withBundle) { builder.addCode("return new $L<>(bundle);", builderSpec.name) .addParameter(ClassName.get(AndroidTypes.Bundle.asMirror(context)), "bundle"); } else { builder.addCode("return new $L<>(new Bundle());", builderSpec.name); } ClassName className = ClassName.get(model.classInfo().fullyQualifiedPackageName, Internal.BUILDER_CLASS_NAME, builderSpec.name); builder.addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(ParameterizedTypeName .get(className, ClassName.get(model.classModel().originatingElement()), var("?"))); return builder; }
Example 2
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 3
Source File: ExperimentListWriter.java From siberi-android with MIT License | 6 votes |
private MethodSpec createGetList(HashMap<String,String> experimentsHashMap) { ClassName string = ClassName.get(String.class); ClassName list = ClassName.get("java.util", "List"); ClassName arrays = ClassName.get("java.util", "Arrays"); TypeName listOfString = ParameterizedTypeName.get(list, string); Iterator entries = experimentsHashMap.entrySet().iterator(); MethodSpec.Builder method = MethodSpec.methodBuilder("getTestList"); method.returns(listOfString) .addModifiers(Modifier.PUBLIC, Modifier.STATIC); StringBuilder builder = new StringBuilder("String array[] = {"); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); builder.append((String) entry.getKey()); if (entries.hasNext()) { builder.append(","); } } builder.append("}"); method.addStatement(builder.toString()) .addStatement("return $T.asList(array)", arrays); return method.build(); }
Example 4
Source File: ExperimentListWriter.java From siberi-android with MIT License | 6 votes |
private MethodSpec createGetParams(HashMap<String,String> experimentsHashMap){ Iterator entries = experimentsHashMap.entrySet().iterator(); ClassName textUtils = ClassName.get("android.text", "TextUtils"); MethodSpec.Builder method = MethodSpec.methodBuilder("getTestNameParams"); method.returns(String.class) .addModifiers(Modifier.PUBLIC, Modifier.STATIC); StringBuilder builder = new StringBuilder("String params[] = {"); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); builder.append((String) entry.getKey()); if (entries.hasNext()) { builder.append(","); } } builder.append("}"); method.addStatement(builder.toString()) .addStatement("return $T.join(\",\", params)",textUtils); return method.build(); }
Example 5
Source File: EventCaseGeneratorTest.java From litho with Apache License 2.0 | 5 votes |
@Test public void testBasicGeneratorCase() { final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("method"); final EventDeclarationModel model = new EventDeclarationModel(ClassName.OBJECT, TypeName.VOID, ImmutableList.of(), null); EventCaseGenerator.builder() .contextClass(ClassNames.COMPONENT_CONTEXT) .eventMethodModels( ImmutableList.of( SpecMethodModel.<EventMethod, EventDeclarationModel>builder() .name("event") .returnTypeSpec(new TypeSpec(TypeName.VOID)) .typeModel(model) .build())) .writeTo(methodBuilder); assertThat(methodBuilder.build().toString()) .isEqualTo( "void method() {\n" + " case 96891546: {\n" + " java.lang.Object _event = (java.lang.Object) eventState;\n" + " event(\n" + " eventHandler.mHasEventDispatcher);\n" + " return null;\n" + " }\n" + "}\n"); }
Example 6
Source File: PassCreate.java From soabase-halva with Apache License 2.0 | 5 votes |
private void addItem(TypeSpec.Builder builder, ImplicitSpec spec, ImplicitItem item) { ExecutableElement method = item.getExecutableElement(); MethodSpec.Builder methodSpecBuilder = (method.getKind() == ElementKind.CONSTRUCTOR) ? MethodSpec.constructorBuilder() : MethodSpec.methodBuilder(method.getSimpleName().toString()); methodSpecBuilder.addModifiers(method.getModifiers().stream().filter(m -> m != Modifier.ABSTRACT).collect(Collectors.toList())); if ( method.getReturnType().getKind() != TypeKind.VOID ) { methodSpecBuilder.returns(ClassName.get(method.getReturnType())); } method.getTypeParameters().forEach(typeParameter -> methodSpecBuilder.addTypeVariable(TypeVariableName.get(typeParameter))); CodeBlock.Builder codeBlockBuilder = CodeBlock.builder(); if ( method.getKind() == ElementKind.CONSTRUCTOR ) { codeBlockBuilder.add("super("); } else if ( method.getReturnType().getKind() == TypeKind.VOID ) { codeBlockBuilder.add("super.$L(", method.getSimpleName()); } else { codeBlockBuilder.add("return super.$L(", method.getSimpleName()); } CodeBlock methodCode = new ImplicitMethod(environment, method, spec, contextItems).build(parameter -> { ParameterSpec.Builder parameterSpec = ParameterSpec.builder(ClassName.get(parameter.asType()), parameter.getSimpleName().toString(), parameter.getModifiers().toArray(new javax.lang.model.element.Modifier[parameter.getModifiers().size()])); methodSpecBuilder.addParameter(parameterSpec.build()); }); codeBlockBuilder.add(methodCode); methodSpecBuilder.addCode(codeBlockBuilder.addStatement(")").build()); builder.addMethod(methodSpecBuilder.build()); }
Example 7
Source File: InitializerSpec.java From spring-init with Apache License 2.0 | 5 votes |
private MethodSpec createInitializer() { MethodSpec.Builder builder = MethodSpec.methodBuilder("initialize"); builder.addAnnotation(Override.class); builder.addModifiers(Modifier.PUBLIC); builder.addParameter(SpringClassNames.GENERIC_APPLICATION_CONTEXT, "context"); addBeanMethods(builder, configurationType); return builder.build(); }
Example 8
Source File: ParameAnnotationGenerator.java From EasyRouter with Apache License 2.0 | 4 votes |
/** * public void injectData(Activity activity){ ((xxxActivity) activity).data = activity.getIntent().getString("data"); } */ private MethodSpec getInjectMethod(List<ParameAnnotationClass> parameAnnatationClasses, ClassName className, boolean isResult) { ClassName activity = ClassName.get("android.app", "Activity"); ClassName message = ClassName.get(Constant.MESSAGE_PACKAGE, "Message"); ClassName baseRouter = ClassName.get(Constant.BASEROUTER_PACKAGE, "BaseRouter"); ClassName datas = ClassName.get(Map.class); ClassName converter = ClassName.get(Constant.COVERTER_PACKAGE, "Converter"); ClassName easyRouterSet = ClassName.get(Constant.EASYROUTERSET_PACKAGE, "EasyRouterSet"); ClassName convertException = ClassName.get(Constant.EXCEPTION_PACKAGE, "ConverterExpection"); ClassName zlog = ClassName.get(Constant.ZLOG_PACKAGE, "ZLog"); ClassName intent = ClassName.get("android.content", "Intent"); MethodSpec.Builder injectDataBuilder; if (isResult) { injectDataBuilder = MethodSpec.methodBuilder("injectResult"); } else { injectDataBuilder = MethodSpec.methodBuilder("injectParam"); } injectDataBuilder.addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(activity, "activity") .addParameter(intent, "intent"); if (parameAnnatationClasses != null) { injectDataBuilder.addStatement("$T message = intent.getParcelableExtra($T.ROUTER_MESSAGE)", message, baseRouter) .addStatement("$T.Body body = message.getBody()", message) .addStatement("$T<String, String> datas = body.getDatas()", datas) .addStatement("$T.Factory factory = $T.getConverterFactory()", converter, easyRouterSet) .beginControlFlow("try"); for (ParameAnnotationClass parameAnnotationClass : parameAnnatationClasses) { injectDataBuilder.addStatement("(($T) activity).$N = ($T) factory.decodeConverter($T.class).convert(datas.get($S))", className, parameAnnotationClass.getParameName(), parameAnnotationClass.getTypeName(), parameAnnotationClass.getTypeName(), parameAnnotationClass.getKey()); } injectDataBuilder.endControlFlow() .beginControlFlow("catch ($T e)", convertException) .addStatement("$T.e($S + e.getMessage())", zlog, className.toString() + "$$Inject") .endControlFlow(); } return injectDataBuilder.build(); }
Example 9
Source File: ShieldClass.java From RHub with Apache License 2.0 | 4 votes |
private TypeSpec generateShieldImpl() { TypeSpec.Builder res = TypeSpec.classBuilder(shieldImplName.simpleName()) .addModifiers(PUBLIC); res.addSuperinterface(shieldInterfaceName); res.addField(ClassName.get(hubClass), "rHub", PRIVATE, FINAL); MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC); constructor.addParameter(ClassName.get(hubClass), "rHub"); constructor.addCode(CodeBlock.builder().addStatement("this.rHub=rHub").build()); res.addMethod(constructor.build()); for (Map.Entry<ExecutableElement, ProxyTagAnnotation> entry : nodes.entrySet()) { ExecutableElement methodEl = entry.getKey(); ProxyTagAnnotation na = entry.getValue(); MethodSpec.Builder methodSpec = MethodSpec.methodBuilder( methodEl.getSimpleName().toString()); methodSpec.addModifiers(PUBLIC); methodSpec.returns(ClassName.get(methodEl.getReturnType())); if (na.isInput()) { methodSpec.addParameter(ParameterSpec.builder(na.paramType, "src").build()); methodSpec.addCode(CodeBlock.builder() .addStatement((na.isInputWithRemovable() ? "return " : "") + "rHub.addUpstream($S,$L)", na.nodeTag, "src").build()); } else { if (na.hasEnclosedClassName()) { methodSpec.addCode(CodeBlock.builder() .addStatement("return rHub.getPub($S,$T.class)", na.nodeTag, na.getEnclosedClassName()) .build()); } else { methodSpec.addCode(CodeBlock.builder() .addStatement("return rHub.getPub($S)", na.nodeTag).build()); } } res.addMethod(methodSpec.build()); } return res.build(); }
Example 10
Source File: MethodGenerator.java From OkDeepLink with Apache License 2.0 | 4 votes |
public MethodSpec.Builder overMethod(String name) { MethodSpec.Builder builder = MethodSpec.methodBuilder(getValidMethodName(name)); addModifiers(builder); addAnnotation(builder); checkParameters(executableElement, builder); addReturnType(executableElement, builder); addExceptions(executableElement, builder); return builder; }
Example 11
Source File: AndroidRouterProcessor.java From Android-Router with Apache License 2.0 | 4 votes |
private void parseRouterModule(Element moduleEle, List<? extends Element> allEle, List<JavaFile> javaFiles) { RouterModule moduleAnno = moduleEle.getAnnotation(RouterModule.class); String schemes = moduleAnno.scheme(); String host = moduleAnno.host().toLowerCase(); if (isEmpty(schemes) || isEmpty(host)) return; // constructor build MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder(); constructorBuilder.addModifiers(Modifier.PUBLIC).addException(Exception.class); // constructor body ClassName original = ClassName.get(elementUtils.getPackageOf(moduleEle).toString(), moduleEle.getSimpleName().toString()); constructorBuilder.addStatement("this.original = $T.class.newInstance()", original) .addStatement("this.mapping = new $T()", HashMap.class); // parse RouterPath int size = allEle.size(); for (int i = 0; i < size; i++) { Element elm = allEle.get(i); RouterPath pathAnno = elm.getAnnotation(RouterPath.class); if (pathAnno == null) continue; String agrs = ((ExecutableElement) elm).getParameters().toString(); String types = ""; String methodFullTypes = elm.toString(); int start = methodFullTypes.indexOf("("); int end = methodFullTypes.indexOf(")"); if (end - start > 1) { // open1(java.lang.String,com.tangxiaolv.router.Promise) => // ,java.lang.String.class,com.tangxiaolv.router.Promise.class)) types = methodFullTypes.substring(start + 1, end); if (types.lastIndexOf("...") != -1) types = types.replace("...", "[]"); methodFullTypes = "," + getFullTypesString(types) + "))"; } else { methodFullTypes = "))"; } String methodKey = pathAnno.value().toLowerCase(); String methodName = elm.getSimpleName().toString(); // add method constructorBuilder.addStatement( "mapping.put($S + $T._METHOD, original.getClass().getMethod($S" + methodFullTypes, methodKey, MODULE_DELEGATER, methodName); // add params name constructorBuilder.addStatement("String args$L = $S", i, agrs); constructorBuilder.addStatement("mapping.put($S + $T._ARGS, args$L)", methodKey, MODULE_DELEGATER, i); // add params type constructorBuilder.addStatement("String type$L = $S", i, types); constructorBuilder.addStatement("mapping.put($S + $T._TYPES, type$L)", methodKey, MODULE_DELEGATER, i) .addCode("\n"); } // method build MethodSpec.Builder invokeBuilder = MethodSpec.methodBuilder("invoke"); invokeBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(void.class) .addParameter(String.class, "path") .addParameter(PARAMS_WRAPPER, "params") .addException(Exception.class); // method body invokeBuilder.addStatement("$T.invoke(path,params,original,mapping)", MODULE_DELEGATER); // check multi schemes String scheme_main = schemes.contains("|") ? schemes.split("\\|")[0] : schemes; // java file build String mirror_name_main = PREFIX + scheme_main + "_" + host; TypeSpec clazz = TypeSpec.classBuilder(mirror_name_main) .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addSuperinterface(IMIRROR) // Fields .addFields(buildRouterModuleFields()) // constructor .addMethod(constructorBuilder.build()) // Methods .addMethod(invokeBuilder.build()) // doc .addJavadoc(FILE_DOC) .build(); JavaFile javaFile = JavaFile.builder(PACKAGE_NAME, clazz).build(); javaFiles.add(javaFile); if (!schemes.equals(scheme_main)) { makeSubFile(schemes, host, ClassName.get(PACKAGE_NAME, mirror_name_main), javaFiles); } }
Example 12
Source File: SurgeonProcessor.java From Surgeon with Apache License 2.0 | 4 votes |
private void generateMasterJavaFile(Map<String, Map<String, Element>> groups, List<JavaFile> javaFiles) { Set<Map.Entry<String, Map<String, Element>>> kvs = groups.entrySet(); for (Map.Entry<String, Map<String, Element>> group : kvs) { String namespace = group.getKey(); if (isEmpty(namespace)) return; Map<String, Element> methodMappings = group.getValue(); // constructor build MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder(); constructorBuilder.addModifiers(Modifier.PUBLIC).addException(Throwable.class); // constructor body constructorBuilder.addStatement("this.mapping = new $T()", HashMap.class); for (Map.Entry<String, Element> mapping : methodMappings.entrySet()) { String fullName = mapping.getKey();//method name + "." + extra Element element = mapping.getValue(); SurgeonMethod sm = parseToSurgeonMethod(element); sm.owner = ClassName.get(((TypeElement) element.getEnclosingElement())); // add method constructorBuilder.addStatement( "mapping.put($S," + "new $T($T.class," + sm.method + ",$S,$S)" + ")", fullName, SurgeonMethod, sm.owner, //method inner sm.owner, element.getSimpleName().toString(), //method inner end sm.simpleParamsName, sm.simpleParamsTypes); //.addCode("\n"); } // method build MethodSpec.Builder invokeBuilder = MethodSpec.methodBuilder("find"); invokeBuilder.addModifiers(Modifier.PUBLIC) .returns(SurgeonMethod) .addParameter(String.class, "name"); // method body invokeBuilder.addStatement("return ($T) mapping.get(name)", SurgeonMethod); // java file build String mirror_name_main = PREFIX + namespace.replace(".", "_"); TypeSpec clazz = TypeSpec.classBuilder(mirror_name_main) .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addSuperinterface(ISurgeonMaster) // Fields .addFields(buildRouterModuleFields()) // constructor .addMethod(constructorBuilder.build()) // Methods .addMethod(invokeBuilder.build()) // doc .addJavadoc(FILE_DOC) .build(); JavaFile javaFile = JavaFile.builder(PACKAGE_NAME, clazz).build(); javaFiles.add(javaFile); } }
Example 13
Source File: WriterUtil.java From sqlitemagic with Apache License 2.0 | 4 votes |
public static MethodSpec.Builder createMagicInvokableMethod(String className, String methodName) { return MethodSpec.methodBuilder(methodName); }
Example 14
Source File: OpenApi2JaxRs.java From apicurio-studio with Apache License 2.0 | 4 votes |
/** * Generates a Jax-rs interface from the given codegen information. * @param _interface */ protected String generateJavaInterface(CodegenJavaInterface _interface) { // Create the JAX-RS interface spec itself. Builder interfaceBuilder = TypeSpec .interfaceBuilder(ClassName.get(_interface.getPackage(), _interface.getName())); interfaceBuilder.addModifiers(Modifier.PUBLIC) .addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "Path")) .addMember("value", "$S", _interface.getPath()).build()) .addJavadoc("A JAX-RS interface. An implementation of this interface must be provided.\n"); // Add specs for all the methods. for (CodegenJavaMethod cgMethod : _interface.getMethods()) { com.squareup.javapoet.MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(cgMethod.getName()); methodBuilder.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT); // The @Path annotation. if (cgMethod.getPath() != null) { methodBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "Path")) .addMember("value", "$S", cgMethod.getPath()).build()); } // The @GET, @PUT, @POST, etc annotation methodBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", cgMethod.getMethod().toUpperCase())).build()); // The @Produces annotation if (cgMethod.getProduces() != null && !cgMethod.getProduces().isEmpty()) { methodBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "Produces")) .addMember("value", "$L", toStringArrayLiteral(cgMethod.getProduces())).build()); } // The @Consumes annotation if (cgMethod.getConsumes() != null && !cgMethod.getConsumes().isEmpty()) { methodBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "Consumes")) .addMember("value", "$L", toStringArrayLiteral(cgMethod.getConsumes())).build()); } // The method return type. if (cgMethod.getReturn() != null) { TypeName returnType = generateTypeName(cgMethod.getReturn().getCollection(), cgMethod.getReturn().getType(), cgMethod.getReturn().getFormat(), true, ClassName.get("javax.ws.rs.core", "Response")); if (getSettings().reactive || cgMethod.isAsync()) { returnType = generateReactiveTypeName(returnType); } methodBuilder.returns(returnType); } // The method arguments. if (cgMethod.getArguments() != null && !cgMethod.getArguments().isEmpty()) { for (CodegenJavaArgument cgArgument : cgMethod.getArguments()) { TypeName defaultParamType = ClassName.OBJECT; if (cgArgument.getIn().equals("body")) { defaultParamType = ClassName.get("java.io", "InputStream"); } TypeName paramType = generateTypeName(cgArgument.getCollection(), cgArgument.getType(), cgArgument.getFormat(), cgArgument.getRequired(), defaultParamType); if (cgArgument.getTypeSignature() != null) { // TODO try to find a re-usable data type that matches the type signature } com.squareup.javapoet.ParameterSpec.Builder paramBuilder = ParameterSpec.builder(paramType, paramNameToJavaArgName(cgArgument.getName())); if (cgArgument.getIn().equals("path")) { paramBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "PathParam")) .addMember("value", "$S", cgArgument.getName()).build()); } if (cgArgument.getIn().equals("query")) { paramBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "QueryParam")) .addMember("value", "$S", cgArgument.getName()).build()); } if (cgArgument.getIn().equals("header")) { paramBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "HeaderParam")) .addMember("value", "$S", cgArgument.getName()).build()); } methodBuilder.addParameter(paramBuilder.build()); } } // TODO:: error responses (4xx and 5xx) // Should errors be modeled in some way? JAX-RS has a few ways to handle them. I'm inclined to // not generate anything in the interface for error responses. // Javadoc if (cgMethod.getDescription() != null) { methodBuilder.addJavadoc(cgMethod.getDescription()); methodBuilder.addJavadoc("\n"); } interfaceBuilder.addMethod(methodBuilder.build()); } TypeSpec jaxRsInterface = interfaceBuilder.build(); JavaFile javaFile = JavaFile.builder(_interface.getPackage(), jaxRsInterface).build(); return javaFile.toString(); }
Example 15
Source File: RetrofitServiceMethod.java From kaif-android with Apache License 2.0 | 4 votes |
private MethodSpec generateCode(boolean withRetryStaleHeader) { MethodSpec.Builder builder = MethodSpec.methodBuilder(getMethodName(withRetryStaleHeader)); builder.addModifiers(Modifier.ABSTRACT).addModifiers(Modifier.PUBLIC); methodElement.getParameters().stream().map(variableElement -> { ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(TypeName.get(variableElement.asType()), variableElement.getSimpleName().toString()); variableElement.getAnnotationMirrors() .stream() .map(AnnotationSpecUtil::generate) .forEach(parameterBuilder::addAnnotation); return parameterBuilder.build(); }).forEach(builder::addParameter); List<AnnotationSpec> annotationSpecs = methodElement.getAnnotationMirrors() .stream() .map(AnnotationSpecUtil::generate) .collect(toList()); if (withRetryStaleHeader) { Optional<AnnotationSpec> header = annotationSpecs.stream() .filter(annotationSpec -> isHeaderAnnotation(annotationSpec)) .findAny(); if (header.isPresent()) { annotationSpecs.forEach(annotationSpec -> { if (isHeaderAnnotation(annotationSpec)) { AnnotationSpec.Builder replace = AnnotationSpec.builder((ClassName) annotationSpec.type); annotationSpec.members.forEach((String s, List<CodeBlock> codeBlocks) -> { codeBlocks.forEach(codeBlock -> { replace.addMember(s, codeBlock); }); }); replace.addMember("value", "$S", CACHE_STALE_HEADER); builder.addAnnotation(replace.build()); } else { builder.addAnnotation(annotationSpec); } }); } else { annotationSpecs.forEach(builder::addAnnotation); builder.addAnnotation(AnnotationSpec.builder(Headers.class) .addMember("value", "$S", CACHE_STALE_HEADER) .build()); } } else { annotationSpecs.forEach(builder::addAnnotation); } return builder.returns(TypeName.get(methodElement.getReturnType())).build(); }
Example 16
Source File: AnnotationCreatorClassPoolVisitor.java From reflection-no-reflection with Apache License 2.0 | 4 votes |
private MethodSpec.Builder createPrefixedMethod(String prefix, String fieldName) { final String capitalizedFieldName = util.createCapitalizedName(fieldName); String methodName = prefix + capitalizedFieldName; return MethodSpec.methodBuilder(methodName); }
Example 17
Source File: ModuleDumperClassPoolVisitor.java From reflection-no-reflection with Apache License 2.0 | 4 votes |
private MethodSpec createLoadClassMethod() { MethodSpec.Builder loadClassMethodBuilder = MethodSpec.methodBuilder("loadClass"); ParameterSpec paramClassName = ParameterSpec.builder(STRING_TYPE_NAME, "className").build(); loadClassMethodBuilder .addModifiers(Modifier.PUBLIC) .returns(CLASS_TYPE_NAME) .addParameter(paramClassName); //fill class list loadClassMethodBuilder.beginControlFlow("switch(className)"); for (Class clazz : classList) { String clazzName = clazz.getName(); final String simpleClazzName = clazz.getSimpleName(); final int endIndex = clazzName.lastIndexOf('.'); if (endIndex == -1) { continue; } final String packageName = clazzName.substring(0, endIndex); loadClassMethodBuilder.beginControlFlow("case $S:", clazzName); loadClassMethodBuilder.addStatement("$T c = Class.forNameSafe($S, true)", CLASS_TYPE_NAME, clazzName); loadClassMethodBuilder.addStatement("classSet.add(c)"); if(clazz.getSuperclass() != null) { loadClassMethodBuilder.addStatement("c.setSuperclass(Class.forNameSafe($S))", clazz.getSuperclass().getName()); } if(clazz.getInterfaces()!=null) { loadClassMethodBuilder.addStatement("Class[] interfaces = new Class[$L]", clazz.getInterfaces().length); loadClassMethodBuilder.addStatement("int indexInterface = 0"); for (Class interfaceClass : clazz.getInterfaces()) { loadClassMethodBuilder.addStatement("interfaces[indexInterface++] = Class.forNameSafe($S)", interfaceClass.getName()); } loadClassMethodBuilder.addStatement("c.setInterfaces(interfaces)"); } for (Object constructorObj : clazz.getConstructors()) { generateConstructor(loadClassMethodBuilder, (Constructor) constructorObj); } for (Field field : clazz.getFields()) { generateField(loadClassMethodBuilder, field); } for (Object methodObj : clazz.getMethods()) { generateMethod(loadClassMethodBuilder, (Method) methodObj); } doGenerateSetReflector(loadClassMethodBuilder, clazz, simpleClazzName, packageName); loadClassMethodBuilder.addStatement("c.setModifiers($L)", clazz.getModifiers()); loadClassMethodBuilder.addStatement("c.setIsInterface($L)", clazz.isInterface()); loadClassMethodBuilder.addStatement("return c"); loadClassMethodBuilder.endControlFlow(); } loadClassMethodBuilder.addStatement("default : return null"); loadClassMethodBuilder.endControlFlow(); return loadClassMethodBuilder.build(); }