MockController代码自动生成

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author qbit
 */
public class SrcGenerator {
    public static void main(String[] args) {
        System.out.println(new SrcGenerator().implSrc(StudentScheduleListener.class));
        System.out.println("___________________");
        System.out.println(new SrcGenerator().implSrc(StudentScheduleController.class));
    }
    private static final String NEW_LINE="\r\n";

    String implSrc(Class<?> controllerInterface){
        String implClassName=implClassName(controllerInterface);
        StringBuilder src=new StringBuilder();
        srcPackage(src,implClassName);
        String simpleName= StringUtils.substringAfterLast(implClassName,".");
        src.append('@').append(RestController.class.getName()).append(NEW_LINE);
        src.append("public class ").append(simpleName).append(" implements ").append(controllerInterface.getName()).append("{").append(NEW_LINE);
        Stream.of(controllerInterface.getMethods()).forEach(method -> this.srcMethod(src,method,controllerInterface));
        src.append("}");
        return src.toString();
    }

    private void srcMethod(StringBuilder src, Method method,Class<?> controllerInterface) {
        if(method.isDefault()){
            return;
        }
        if(method.getReturnType()== List.class){
            listMethod(src,method,controllerInterface);
            return;
        }
        src.append("public ").append(toString(GenericTypeResolver.resolveReturnType(method,controllerInterface)))
                .append(" ").append(method.getName()).append("(").append(NEW_LINE);

        srcParameters(src, method);

        if(void.class!=method.getReturnType()){
            src.append("return ").append(MockUtils.class.getName()).append(".mock(").append(toString(method.getReturnType())).append(".class);").append(NEW_LINE);
        }
        src.append("}").append(NEW_LINE);
    }

    private void srcParameters(StringBuilder src, Method method) {
        final int length=method.getParameterCount();
        for(int i=0;i<length;i++){
            srcParameter(src, new MethodParameter(method,i));
            if(length-1==i){
                src.append("){");
            }else{
                src.append(',');
            }
            src.append(NEW_LINE);
        }
    }
    private String toString(Type clazz){
        return clazz.getTypeName().replace('$','.');
    }
    private void listMethod(StringBuilder src, Method method, Class<?> controllerInterface) {
        final String className=toString(ResolvableType.forMethodReturnType(method,controllerInterface).getNested(2).getType());
        src.append("public java.util.List<").append(className).append("> ").append(method.getName()).append ("(").append(NEW_LINE);
        srcParameters(src,method);
        src.append("return ").append(MockUtils.class.getName()).append(".mockList(").append(className).append(".class);").append(NEW_LINE);
        src.append("}").append(NEW_LINE);
    }

    private void srcParameter(StringBuilder src, MethodParameter methodParameter) {
        Stream.of(methodParameter.getParameterAnnotations()).forEach(annotation -> srcAnnotation(src,annotation));
        src.append(ResolvableType.forMethodParameter(methodParameter).toString().replace('$','.')).append(" ").append(getParameterName(methodParameter));
    }

    private String getParameterName(MethodParameter methodParameter) {
        if(null!=methodParameter.getParameterName()){
            return methodParameter.getParameterName();
        }else{
            var pathVariable=methodParameter.getParameterAnnotation(PathVariable.class);
            if(null!=pathVariable){
                String id=pathVariable.value();
                if(StringUtils.isEmpty(id)){
                    id="id";
                }
                return id;
            }
            var parameterType=methodParameter.getParameter().getType();
            if(parameterType==List.class){
                return getParameterNameByClass(ResolvableType.forMethodParameter(methodParameter).getNested(1))+"s";
            }else{
                return getParameterNameByClass(ResolvableType.forMethodParameter(methodParameter));
            }
        }
    }

    private String getParameterNameByClass(ResolvableType methodParameter) {
        String className=methodParameter.getType().getTypeName();
        for(String postfix:new String[]{"Query","DTO","TO","Command","Event","Message"}){
            if(className.endsWith(postfix)){
                return postfix.toLowerCase();
            }
        }
        return "arg";
    }

    private void srcAnnotation(StringBuilder src, Annotation annotation) {
        src.append(annotation).append(" ");
    }

    private void srcPackage(StringBuilder src, String implClassName) {
        src.append("package ")
                .append(StringUtils.substringBeforeLast(implClassName,"."))
                .append(';')
                .append(NEW_LINE);
    }

    public String implClassName(Class<?> controllerInterface) {
        String interfaceName=controllerInterface.getSimpleName();
        for(String postfix:new String[]{"Controller","Service","Listener"}){
            if(interfaceName.endsWith(postfix)){
                return "mock."+controllerInterface.getPackageName()+'.'+
                        interfaceName.substring(0,interfaceName.length()-postfix.length());
            }
        }
        throw new IllegalArgumentException("can not generate impl class name for "+controllerInterface);
    }
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值