Java Codemodel - Annotate a method or class

孤街浪徒 提交于 2019-12-12 14:40:22

问题


I am using CodeModel to programmatically generate .java files. This is a snippet of code to create a method:

JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");

//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");

When I run (assume all other necessary codes are there);

public String getCustomerInfo() { }

But I want to annotate above method like this:

@GET
@Path("/getCustomerInfo")
public String getCustomerInfo() { }

For which I tried below methods: method.annotate(...) and method.annotate2(...)

But those methods accept only Class files as a arguments (ie like in the form SomeClass.class), but I want to be able to String as an argument and that class will be available dynamically at run time.

Say I should be able to do like this: method.annotate("Path").

Can anyone help me?


回答1:


You can use JClass which can be constructed from a String or Class:

JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");

//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");

method.annotate(jCodeModel.ref("javax.ws.rs.GET"));
method.annotate(jCodeModel.ref("javax.ws.rs.Path")).param("value", "/getCustomerInfo");

or

method.annotate(jCodeModel.ref(javax.ws.rs.GET));
method.annotate(jCodeModel.ref(javax.ws.rs.Path)).param("value", "/getCustomerInfo");



回答2:


There's also a variant that takes a JClass, so you have to either:

  • have the annotation on your classpath or
  • generate the annotation with the JCodeModel

As far as I can see, that's pretty much the same approach as with all other uses of classes, I don't see how annotations should be different here.




回答3:


You can do on your Method something like this:

yourJMethod.annotate(YourClass.class); 



回答4:


public void setControllerMapping(Pagemaster pagemaster)  throws Exception
        {
            // Instantiate a new JCodeModel
            JCodeModel codeModel = new JCodeModel();

            // Create a new class

            JDefinedClass mappingController = codeModel._class("com.discom.springmvc.controllerTemp.ViewUrlController"+pagemaster.getUrl());
            mappingController.annotate(codeModel.ref("org.springframework.stereotype.Controller"));
            mappingController.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/");
            mappingController.annotate(codeModel.ref("org.springframework.web.bind.annotation.SessionAttributes")).param("value", "roles");

            JFieldVar jSearchDao = mappingController.field(JMod.NONE, SearchDao.class, "searchDao");
            jSearchDao.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
            JFieldVar jAddService = mappingController.field(JMod.NONE, AddService.class, "addService");
            jAddService.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
            JFieldVar httpSession = mappingController.field(JMod.PRIVATE, HttpSession.class, "httpSession");
            httpSession.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
            JFieldVar listService = mappingController.field(JMod.PRIVATE, ListService.class, "listService");
            listService.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
            /*codeModel.directClass("java.util.Date");
            codeModel.directClass("java.sql.Timestamp");
            codeModel.directClass("org.springframework.http.HttpStatus");
            codeModel.directClass("org.springframework.security.core.context.SecurityContextHolder");
            codeModel.directClass("org.springframework.security.core.userdetails.UserDetails");
            codeModel.directClass("com.fasterxml.jackson.databind.ObjectMapper");
            codeModel.directClass("java.util.List");*/
            JFieldVar saveDate = mappingController.field(JMod.NONE, Date.class, "saveDatee");
            JFieldVar timeStampDate = mappingController.field(JMod.NONE, Timestamp.class, "timeStampDatee");
            JFieldVar httpStatus = mappingController.field(JMod.NONE, HttpStatus.class, "httpStatuss");
            JFieldVar securityContextHolder = mappingController.field(JMod.NONE, SecurityContextHolder.class, "securityContextHolder");
            JFieldVar userDetails = mappingController.field(JMod.NONE, UserDetails.class, "userDetails");
            JFieldVar objectMapper = mappingController.field(JMod.NONE, ObjectMapper.class, "objectMapperr");
            JFieldVar listt = mappingController.field(JMod.NONE, List.class, "listt");

            // Add Mapping method
            JMethod mappingMethod = mappingController.method(JMod.PUBLIC, String.class, pagemaster.getUrl()+"URL");
            JVar model = mappingMethod.param(ModelMap.class, "model");
            mappingMethod.body().invoke(model, "addAttribute").arg("pagemaster").arg(jSearchDao.invoke("findPagemasterByUrl").arg(pagemaster.getUrl()));
            mappingMethod.body().invoke(model, "addAttribute").arg("submenu").arg(jSearchDao.invoke("findSubMenuById").arg(jSearchDao.invoke("findPagemasterByUrl").arg(pagemaster.getUrl()).invoke("getSubmenuId").invoke("toString")));
            mappingMethod.body().invoke(model, "addAttribute").arg("fieldsList").arg(jSearchDao.invoke("getTemplateFieldsList").arg(jSearchDao.invoke("findPagemasterByUrl").arg(pagemaster.getUrl()).invoke("getTemplateId").invoke("toString")));
            mappingMethod.body()._return(JExpr.ref("\""+pagemaster.getUrl()+"Def\""));
            mappingMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/"+pagemaster.getUrl()).param("method", RequestMethod.GET);

            // Add Save method
            JMethod saveMethod = mappingController.method(JMod.PUBLIC, codeModel.ref(ResponseEntity.class).narrow(String.class), "save"+pagemaster.getPageTitle().replace(" ", ""));
            List<TemplateFields> reqFields = searchDao.getTemplateFieldsList(pagemaster.getTemplateId().toString());
            for(TemplateFields tf:reqFields)
            {
                if(!tf.getFieldName().equals("id") && !tf.getFieldName().contains("created") && !tf.getFieldName().contains("updated"))
                {
                    JVar reqParam = saveMethod.param(getDataType(tf.getFieldType()), tf.getFieldName());
                    if(tf.getIsNull()==false)
                        reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName());
                    else
                        reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName()).param("required", false);
                }   
            }
            Template template = reqFields.get(0).getTemplateId();
            JFieldVar templateTableName = mappingController.field(JMod.NONE, codeModel.ref("com.discom.springmvc.pojo."+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)), template.getTablename()+"Obj");
            saveMethod.body().directStatement("Date saveDate = new Date();");
            saveMethod.body().directStatement("Timestamp timeStampDate = new Timestamp(saveDate.getTime());");
            saveMethod.body().directStatement(template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" "+template.getTablename()+" = new "+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"();");
            for(TemplateFields tf:reqFields)
            {
                if(tf.getFieldName().equals("id"))
                {
                    saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(null);");
                }
                else if(tf.getFieldName().equals("createdBy") || tf.getFieldName().equals("updatedBy"))
                {
                    saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(getPrincipal());");
                }
                else if(tf.getFieldName().equals("createdOn") || tf.getFieldName().equals("updatedOn"))
                {
                    saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(timeStampDate);");
                }
                else
                {
                    saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"("+tf.getFieldName()+");");
                }
            }
            saveMethod.body().directStatement("boolean sts = false;");
            saveMethod.body().directStatement("// create save method first");
            saveMethod.body().directStatement("//sts = addService.save"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"("+template.getTablename()+");");
            saveMethod.body().directStatement("if(sts==false){");
            saveMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" not saved.\",HttpStatus.BAD_REQUEST);");
            saveMethod.body().directStatement("}");
            saveMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" Successfully saved.\",HttpStatus.OK);");
            saveMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/save"+pagemaster.getPageTitle().replace(" ", "")).param("method", RequestMethod.POST);


            // Add Update method
            JMethod updateMethod = mappingController.method(JMod.PUBLIC, codeModel.ref(ResponseEntity.class).narrow(String.class), "update"+pagemaster.getPageTitle().replace(" ", ""));
            for(TemplateFields tf:reqFields)
            {
                if(!tf.getFieldName().contains("created") && !tf.getFieldName().contains("updated"))
                {
                    JVar reqParam = updateMethod.param(getDataType(tf.getFieldType()), tf.getFieldName());
                    if(tf.getIsNull()==false)
                        reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName());
                    else
                        reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName()).param("required", false);
                }   
            }
            updateMethod.body().directStatement("Date saveDate = new Date();");
            updateMethod.body().directStatement("Timestamp timeStampDate = new Timestamp(saveDate.getTime());");
            updateMethod.body().directStatement(template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" "+template.getTablename()+" = null; // create search methods //searchDao.find"+template.getTablename().substring(0, 1).toUpperCase()+template.getTablename().substring(1)+"ById(id.toString());");
            for(TemplateFields tf:reqFields)
            {
                if(tf.getFieldName().equals("id"))
                {

                }
                else if(tf.getFieldName().equals("updatedBy"))
                {
                    updateMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(getPrincipal());");
                }
                else if(tf.getFieldName().equals("updatedOn"))
                {
                    updateMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(timeStampDate);");
                }
                else if(tf.getFieldName().equals("createdBy"))
                {

                }
                else if(tf.getFieldName().equals("createdOn"))
                {

                }
                else
                {
                    updateMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"("+tf.getFieldName()+");");
                }
            }
            updateMethod.body().directStatement("boolean sts = false;");
            updateMethod.body().directStatement("// create update method first");
            updateMethod.body().directStatement("//sts = addService.update"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"("+template.getTablename()+");");
            updateMethod.body().directStatement("if(sts==false){");
            updateMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" not updated.\",HttpStatus.BAD_REQUEST);");
            updateMethod.body().directStatement("}");
            updateMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" Successfully updated.\",HttpStatus.OK);");
            updateMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/update"+pagemaster.getPageTitle().replace(" ", "")).param("method", RequestMethod.POST);


            // Add DataTable List method
            JMethod dtMethod = mappingController.method(JMod.PUBLIC, (codeModel.ref(String.class)), "list"+pagemaster.getPageTitle().replace(" ", ""));
            dtMethod._throws(Exception.class);
            JVar startReqParam = dtMethod.param(int.class, "start");
            startReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam"));
            JVar lengthReqParam = dtMethod.param(int.class, "length");
            lengthReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam"));
            JVar searchReqParam = dtMethod.param(String.class, "search");
            searchReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", "search[value]");
            List<String> filAssN = new ArrayList<String>();
            List<String> filAssV = new ArrayList<String>();
            String printS = "";
            int fSize = 0;
            for(TemplateFields tf:reqFields)
            {
                if(!tf.getFieldName().equals("id") && !tf.getFieldName().contains("created") && !tf.getFieldName().contains("updated"))
                {
                    JVar reqParam = dtMethod.param(String.class, tf.getFieldName());
                    reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName());
                    filAssN.add("list["+fSize+"]=null;");
                    filAssV.add("if("+tf.getFieldName()+"!=null && !"+tf.getFieldName()+".equals(\"\"))");
                    filAssV.add("list["+fSize+"]="+tf.getFieldName()+";");
                    if(fSize==0)
                        printS += "\""+tf.getFieldName()+" :\"+"+tf.getFieldName()+"";
                    else
                        printS += "+\" "+tf.getFieldName()+" :\"+"+tf.getFieldName()+"";
                    fSize++;
                }   
            }
            JVar datatReqParam = dtMethod.param(String.class, "datat");
            datatReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", "datat");
            dtMethod.body().directStatement("String list[]=new String["+fSize+"];");
            for(String s:filAssN)
            {
                dtMethod.body().directStatement(s);
            }               
            dtMethod.body().directStatement("System.out.println("+ printS +"+\" datat: \"+datat);");
            for(String s:filAssV)
            {
                dtMethod.body().directStatement(s);
            }   
            dtMethod.body().directStatement("DataTablesTO<"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"> dt = new DataTablesTO<"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+">();");
            dtMethod.body().directStatement("String sessid=(String) httpSession.getId();");
            dtMethod.body().directStatement(template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" "+template.getTablename()+" = null; // create search methods //searchDao.find"+template.getTablename().substring(0, 1).toUpperCase()+template.getTablename().substring(1)+"ById(id.toString());");
            dtMethod.body().directStatement("if(sessid!=null) {");
            dtMethod.body().directStatement("String token= (String)httpSession.getAttribute(\"token\");");
            dtMethod.body().directStatement("if(token.equals(datat)) {");
            dtMethod.body().directStatement("List<"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"> accts = null; //create list method // listService.getAll"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"List(start,length, search, list);");
            dtMethod.body().directStatement("int count = 0; //create list count method // listService.getAll"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"ListCount(search, list);");
            dtMethod.body().directStatement("System.out.println(\"accts___ \"+accts.size()+\" count: \"+count);");
            dtMethod.body().directStatement("dt.setAaData(accts);");
            dtMethod.body().directStatement("dt.setiTotalDisplayRecords(count);");
            dtMethod.body().directStatement("dt.setiTotalRecords(count);");
            dtMethod.body().directStatement("dt.setsEcho(0);");
            dtMethod.body().directStatement("}");
            dtMethod.body().directStatement("}");
            dtMethod.body().directStatement("System.out.println(\"toJson(dt)___ \"+toJson(dt));");
            dtMethod.body().directStatement("return toJson(dt);");
            dtMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/list"+pagemaster.getPageTitle().replace(" ", ""));


            // getPrincipal Mapping method
            JMethod principalMethod = mappingController.method(JMod.PRIVATE, String.class, "getPrincipal");
            principalMethod.body().directStatement("String userName = null;");
            principalMethod.body().directStatement("Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();");
            principalMethod.body().directStatement("if (principal instanceof UserDetails) {");
            principalMethod.body().directStatement("userName = ((UserDetails)principal).getUsername();");
            principalMethod.body().directStatement("} else {");
            principalMethod.body().directStatement("userName = principal.toString();");
            principalMethod.body().directStatement("}");
            principalMethod.body().directStatement("return userName;");

            // getJson Mapping method
            JMethod jsonMethod = mappingController.method(JMod.PRIVATE, String.class, "toJson");
            //codeModel.ref(DataTablesTO.class).narrow(String.class)
            jsonMethod.param(codeModel.ref(DataTablesTO.class).narrow(codeModel.ref(Object.class).wildcard()), "dt");
            jsonMethod.body().directStatement("ObjectMapper mapper = new ObjectMapper();");
            jsonMethod.body().directStatement("try {");
            jsonMethod.body().directStatement("return mapper.writeValueAsString(dt);");
            jsonMethod.body().directStatement("} catch (Exception e) {");
            jsonMethod.body().directStatement("e.printStackTrace();");
            jsonMethod.body().directStatement("return null;");
            jsonMethod.body().directStatement("}");

            // Generate the code
            //JFormatter f = new JFormatter(codeModel.);
            codeModel.build(new File("F:/UISOFT/uisoft/DISCOM/src/main/java/"));
            //codeModel.build(new File(getPath()+"src/main/java/"));
        }



回答5:


public class AppendJavaCode {

    public List<String> getExistingFileData(String permFile, String newPojoClassPath) throws Exception {

        System.out.println("Existing File DATA...............................................\n");
        List<String> listListFileAdd = new ArrayList<String>();
        try {
        BufferedReader in = new BufferedReader(new FileReader(permFile));
        List<String> listListFile = new ArrayList<String>();
        String str = in.readLine();
        while (str!= null) {
            listListFile.add(str);
            str = in.readLine();
            }
        in.close();

        int ii=0;
        for(int i=0;i<listListFile.size();i++)
        {
            if(i==(listListFile.size()-1))
            {

            }
            else
            {
                listListFileAdd.add(listListFile.get(i));
                if(listListFile.get(i).contains("import") && ii==0)
                {
                    listListFileAdd.add(newPojoClassPath);
                    ii++;
                }
            }
        }

        for(String s:listListFileAdd)
        {
            System.out.print(s+"\n");
        }        

        } catch (Exception e) {
        }
        return listListFileAdd;
    }

    public List<String> getNewFileData(String tmpFile) throws Exception {

        System.out.println("New File DATA...............................................\n");
        List<String> listListFileAdd = new ArrayList<String>();
        try {
        BufferedReader in = new BufferedReader(new FileReader(tmpFile));
        List<String> listListFile = new ArrayList<String>();
        String str = in.readLine();
        while (str!= null) {
            listListFile.add(str);
            str = in.readLine();
            }
        in.close();

        int ind=0;
        for(int i=0;i<listListFile.size();i++)
        {
            if(listListFile.get(i).contains("RequestMapping(va"))
            {
                ind = i;
                break;
            }
        }
        for(int i=0;i<listListFile.size();i++)
        {
            if(i>=ind)
            {
                listListFileAdd.add(listListFile.get(i));
            }
        }

        for(String s:listListFileAdd)
        {
            System.out.print(s+"\n");
        }

        } catch (Exception e) {
        }
        return listListFileAdd;
    }

    public void appendDataInFile(String permFile, List<String> existedData, List<String> newData) throws Exception {

        try {
            // create a writer for permFile
            BufferedWriter out = new BufferedWriter(new FileWriter(permFile, false));

            for(int i=0;i<existedData.size();i++)
            {
                out.write(existedData.get(i)+"\n");
            }
            for(int i=0;i<newData.size();i++)
            {
                out.write(newData.get(i)+"\n");
            }

            out.close();

            } catch (Exception e) {
            }
    }

    public static void main(String[] args) throws Exception {

          AppendJavaCode appendJavaCode = new AppendJavaCode();
          // Define two filenames:
          String permFile = "E:/ViewUrlController.java";
          String tmpFile =  "E:/ViewUrlControllerGen.java";
          String newPojoClassPath = "import com.discom.springmvc.pojo.Studentinfo;";

          List<String> existedData = appendJavaCode.getExistingFileData(permFile,newPojoClassPath);
          List<String> newData = appendJavaCode.getNewFileData(tmpFile);
          appendJavaCode.appendDataInFile(permFile, existedData, newData);

          }

}


来源:https://stackoverflow.com/questions/19853943/java-codemodel-annotate-a-method-or-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!