All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.jbock.context.Impl Maven / Gradle / Ivy

There is a newer version: 5.18
Show newest version
package net.jbock.context;

import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import net.jbock.annotated.AnnotatedMethod;
import net.jbock.convert.Mapping;
import net.jbock.processor.SourceElement;

import javax.inject.Inject;
import java.util.List;
import java.util.stream.Collectors;

import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.STATIC;

/**
 * Defines the *Impl inner class.
 *
 * @see GeneratedClass
 */
@ContextScope
public class Impl {

    private final GeneratedTypes generatedTypes;
    private final SourceElement sourceElement;
    private final List> everything;

    @Inject
    Impl(GeneratedTypes generatedTypes,
         SourceElement sourceElement,
         List> everything) {
        this.generatedTypes = generatedTypes;
        this.sourceElement = sourceElement;
        this.everything = everything;
    }

    TypeSpec define() {
        TypeSpec.Builder spec = TypeSpec.classBuilder(generatedTypes.implType());
        if (sourceElement.isInterface()) {
            spec.addSuperinterface(sourceElement.typeName());
        } else {
            spec.superclass(sourceElement.typeName());
        }
        for (Mapping c : everything) {
            spec.addField(c.asField());
        }
        return spec.addModifiers(PRIVATE, STATIC)
                .addMethod(implConstructor())
                .addMethods(everything.stream()
                        .map(this::parameterMethodOverride)
                        .collect(Collectors.toUnmodifiableList()))
                .build();
    }

    private MethodSpec parameterMethodOverride(Mapping c) {
        AnnotatedMethod param = c.sourceMethod();
        return MethodSpec.methodBuilder(param.methodName())
                .returns(TypeName.get(param.returnType()))
                .addModifiers(param.accessModifiers())
                .addStatement("return $N", c.asField())
                .build();
    }

    private MethodSpec implConstructor() {
        MethodSpec.Builder spec = MethodSpec.constructorBuilder();
        for (Mapping c : everything) {
            FieldSpec field = c.asField();
            spec.addStatement("this.$N = $N", field, c.asParam());
            spec.addParameter(c.asParam());
        }
        return spec.build();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy