Java Code Examples for com.squareup.javapoet.MethodSpec#constructorBuilder()

The following examples show how to use com.squareup.javapoet.MethodSpec#constructorBuilder() . 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: FeatureCodeBrewer.java    From featured with Apache License 2.0 6 votes vote down vote up
@Override
public void onMethodEnter(MethodNode methodElement) {
    mEventClassName = mNames.getEventClassName(methodElement);

    mEventTypeBuilder = TypeSpec.classBuilder(mEventClassName)
            .addModifiers(Modifier.STATIC, Modifier.FINAL)
            .superclass(mNames.getEventSuperClassName());

    if (methodElement.hasParameters()) {
        mEventConstructorBuilder = MethodSpec.constructorBuilder();
        mListedFields = prepareStringBuilder(mListedFields);
        mListedParams = prepareStringBuilder(mListedParams);
    }

    mEventDispatchMethodBuilder = MethodSpec
            .methodBuilder(mNames.getDispatchMethodName(methodElement))
            .addModifiers(Modifier.PUBLIC);
}
 
Example 2
Source File: ModuleDumperClassPoolVisitor.java    From reflection-no-reflection with Apache License 2.0 6 votes vote down vote up
private MethodSpec createConstructor() {
    MethodSpec.Builder constructorSpecBuilder = MethodSpec.constructorBuilder();
    constructorSpecBuilder.addModifiers(Modifier.PUBLIC);

    ClassName setTypeName = ClassName.get("java.util", "Set");
    TypeName setOfStringTypeName = ParameterizedTypeName.get(setTypeName, STRING_TYPE_NAME);
    ClassName hashSetTypeName = ClassName.get("java.util", "HashSet");

    int annotationClassCounter = 0;
    for (Map.Entry<Class<? extends Annotation>, Set<Class<?>>> entry : mapAnnotationTypeToClassContainingAnnotation.entrySet()) {
        constructorSpecBuilder.addStatement("$T s$L = new $T()", setOfStringTypeName, annotationClassCounter, hashSetTypeName);
        for (Class<?> clazz : entry.getValue()) {
            constructorSpecBuilder.addStatement("s$L.add($S)", annotationClassCounter, clazz.getName());
        }
        String annotationTypeName = entry.getKey().getName();
        constructorSpecBuilder.addStatement("mapAnnotationNameToNameOfClassesContainingAnnotation.put($S,s$L)", annotationTypeName, annotationClassCounter);
        constructorSpecBuilder.addCode("\n");
        annotationClassCounter++;
    }
    return constructorSpecBuilder.build();
}
 
Example 3
Source File: PassCreate.java    From soabase-halva with Apache License 2.0 5 votes vote down vote up
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 4
Source File: EntityGenerator.java    From requery with Apache License 2.0 5 votes vote down vote up
private void generateConstructors(TypeSpec.Builder builder) {
    // copy the existing constructors
    for (ExecutableElement constructor : ElementFilter.constructorsIn(
            typeElement.getEnclosedElements())) {
        // constructor params
        List<? extends VariableElement> parameters = constructor.getParameters();

        if (!parameters.isEmpty()) {

            MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder();
            constructorBuilder.addModifiers(constructor.getModifiers());

            List<String> parameterNames = new ArrayList<>();
            for (VariableElement parameter : parameters) {
                Modifier[] modifiers = parameter.getModifiers().toArray(
                        new Modifier[parameter.getModifiers().size()]);
                String parameterName = parameter.getSimpleName().toString();
                parameterNames.add(parameterName);
                ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(
                        TypeName.get(parameter.asType()), parameterName, modifiers);
                constructorBuilder.addParameter(parameterBuilder.build());
            }
            // super parameter/arguments
            StringJoiner joiner = new StringJoiner(",", "(", ")");
            parameterNames.forEach(joiner::add);
            constructorBuilder.addStatement("super" + joiner.toString());
            builder.addMethod(constructorBuilder.build());
        }
    }
}
 
Example 5
Source File: LocalCacheContext.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public LocalCacheContext(TypeName superClass, String className, boolean isFinal,
    Set<Feature> parentFeatures, Set<Feature> generateFeatures) {
  this.isFinal = isFinal;
  this.className = className;
  this.superClass = superClass;
  this.parentFeatures = parentFeatures;
  this.generateFeatures = generateFeatures;
  this.cache = TypeSpec.classBuilder(className);
  this.constructor = MethodSpec.constructorBuilder();
}
 
Example 6
Source File: AutoCodecProcessor.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Adds fields to the codec class to hold offsets and adds a constructor to initialize them.
 *
 * <p>For a parameter with name {@code target}, the field will have name {@code target_offset}.
 *
 * @param parameters constructor parameters
 */
private void initializeUnsafeOffsets(
    TypeSpec.Builder builder,
    TypeElement encodedType,
    List<? extends VariableElement> parameters) {
  MethodSpec.Builder constructor = MethodSpec.constructorBuilder();
  for (VariableElement param : parameters) {
    Optional<FieldValueAndClass> field =
        getFieldByNameRecursive(encodedType, param.getSimpleName().toString());
    if (!field.isPresent()) {
      // Will attempt to use a getter for this field instead.
      continue;
    }
    builder.addField(
        TypeName.LONG, param.getSimpleName() + "_offset", Modifier.PRIVATE, Modifier.FINAL);
    constructor.beginControlFlow("try");
    constructor.addStatement(
        "this.$L_offset = $T.getInstance().objectFieldOffset($T.class.getDeclaredField(\"$L\"))",
        param.getSimpleName(),
        UnsafeProvider.class,
        ClassName.get(field.get().declaringClassType),
        param.getSimpleName());
    constructor.nextControlFlow("catch ($T e)", NoSuchFieldException.class);
    constructor.addStatement("throw new $T(e)", IllegalStateException.class);
    constructor.endControlFlow();
  }
  builder.addMethod(constructor.build());
}
 
Example 7
Source File: SurgeonProcessor.java    From Surgeon with Apache License 2.0 4 votes vote down vote up
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 8
Source File: AndroidRouterProcessor.java    From Android-Router with Apache License 2.0 4 votes vote down vote up
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 9
Source File: AndroidRouterProcessor.java    From Android-Router with Apache License 2.0 4 votes vote down vote up
private void makeSubFile(String scheme, String host, ClassName main, List<JavaFile> javaFiles) {
    String[] schemes = scheme.split("\\|");
    for (int i = 1; i < schemes.length; i++) {
        String subScheme = schemes[i];

        // filed build
        FieldSpec f_main = FieldSpec.builder(Object.class, "main")
                .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                .build();

        // constructor build
        MethodSpec.Builder constructor = MethodSpec.constructorBuilder();
        constructor.addModifiers(Modifier.PUBLIC)
                .addException(IllegalAccessException.class)
                .addException(InstantiationException.class)
                .addStatement("this.main = $T.class.newInstance()", main);

        // method build
        MethodSpec.Builder invoke = MethodSpec.methodBuilder("invoke")
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .returns(void.class)
                .addParameter(String.class, "path")
                .addParameter(PARAMS_WRAPPER, "params")
                .addException(Exception.class)
                .addStatement(
                        "main.getClass().getMethod(\"invoke\",String.class,$T.class).invoke(main, path, params)",
                        PARAMS_WRAPPER);

        // java file build
        String mirror_name_sub = PREFIX + subScheme + "_" + host;
        TypeSpec clazz = TypeSpec.classBuilder(mirror_name_sub)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addSuperinterface(IMIRROR)
                .addField(f_main)
                // constructor
                .addMethod(constructor.build())
                // Methods
                .addMethod(invoke.build())
                // doc
                .addJavadoc(FILE_DOC)
                .build();

        JavaFile javaFile = JavaFile.builder(PACKAGE_NAME, clazz).build();
        javaFiles.add(javaFile);
    }
}
 
Example 10
Source File: AddConstructors.java    From caffeine with Apache License 2.0 4 votes vote down vote up
/** Adds the constructor used to create a factory. */
private void addConstructorDefault() {
  context.constructorDefault = MethodSpec.constructorBuilder();
}