使用codemodel生成Java代码

例子

        JCodeModel cm = new JCodeModel();
        JDefinedClass dc = cm._class("foo.Bar");
        dc.annotate(cm.ref("org.springframework.stereotype.Repository")).param("value", "apnService");

        dc.field(JMod.PRIVATE + JMod.STATIC, cm.parseType("String"), "staticVar", JExpr.lit("abc"));
         dc.field(JMod.PUBLIC + JMod.STATIC + JMod.FINAL, cm.INT, "MAX_ARRAY_SIZE", JExpr.lit(25));

        JArray array = JExpr.newArray(cm.parseType("String")); // 创建类型为数组
        dc.field(JMod.PUBLIC + JMod.STATIC + JMod.FINAL, cm.parseType("String[]"), "SORTS", array);
        array.add(JExpr.lit("createdAt"));
        array.add(JExpr.lit("updatedAt"));

        JMethod m = dc.method(0, int.class, "foo");
        m.body()._return(JExpr.lit(5));

        JMethod m2 = dc.method(JMod.PUBLIC, cm.VOID, "bar");
        m2.javadoc().add("This method will say Hello to the name.");
        m2.annotate(Override.class);
        m2.annotate(cm.ref("javax.ws.rs.GET"));
        m2.annotate(cm.ref("javax.ws.rs.Path")).param("value", "/getCustomerInfo").param("name", "appPushMessageMapper");
        JBlock block = m2.body();
        JType type = cm.parseType("String");
        JVar var = block.decl(type, "fieldVar");
        JVar var1 = block.decl(type, "fieldVar1", JExpr.lit("test"));
        JType typeMap2 = cm.ref("java.util.Map").narrow(cm.ref("String"), cm.ref("Object"));
        JType typeMap3 = cm.ref("java.util.HashMap").narrow(cm.ref("String"), cm.ref("Object"));
        block.decl(typeMap2, "map", JExpr._new(typeMap3));


        JAnnotationUse ja;
        JMethod m3 = dc.method(JMod.PUBLIC, cm.parseType("String"), "get");
        JVar jv = m3.param(cm.parseType("String"), "id");
        ja = jv.annotate(cm.ref("Param")).param("value", "id");
        jv = m3.param(cm.ref("java.lang.String"), "site");
        ja = jv.annotate(cm.ref("javax.jws.WebParam"));

        // construct a Map<String, Integer>
        JType typeMap = cm.ref("java.util.Map").narrow(cm.ref("String"), cm.ref("Object"));
        jv = m3.param(typeMap, "args");
        ja = jv.annotate(cm.ref("Param")).param("value", "params");

        File file = new File("d:/home/tomcat/code/");
        file.mkdirs();
        cm.build(file);

 

posted on 2016-10-17 01:39  Milton  阅读(605)  评论(0编辑  收藏  举报

导航