没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
有时候需要在运行时根据模板和数据动态生成 Java 代码,然后对其进行编译生成 Class 文件,然后再将这些类加载
进去,并使用反射来创建对象。
这里面有几个注意点:
需要事先定义一个模板文件
编译的过程中需要依赖一些 Jar 包才能编译成功
编译生成的包路径要放置在特定的地点方便加载
因此,编译过程中涉及到 4 个目录:template 目录、src 目录、classes 目录、jars 目录。template 目录用于放置模板,
src 目录用于放置生成的 java 文件,classes 目录用于放置编译后生成的 class 文件,jars 目录用于放置编译过程中需要的依
赖包。
下面以我的代码为例进行说明:
模板文件 RtTemplateController.java:
package com.nana.cloud.putdata.controller;
import com.nana.cloud.putdata.service.impl.DataReceiveServiceImpl;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("${controllerUrl}")
@EnableSwagger2
@Api(description = "${controllerDesc}", tags = "${controllerTags}")
public class ${className} {
@Autowired
private HttpServletRequest request;
@Autowired
DataReceiveServiceImpl dataReceiveServiceImpl;
@ApiOperation(value = "${uploadMethodDesc}", notes = "${uploadMethodDesc}")
@RequestMapping(value = "${uploadMethodUrl}", method = RequestMethod.POST, consumes =
MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> ${uploadMethodName}(@RequestBody @ApiParam(value = "数据", required = true) String data)
{
return dataReceiveServiceImpl.sendDataToKafka(request, "${configFileName}", data);
}
}
模板文件中有很多可替换项,包括类名,用于后期替换成实际值,从而生成新的 Java 文件(注意,模板文件以 UTF-8
编码)。
生成代码的方法:
资源评论
高阶圣堂武士
- 粉丝: 0
- 资源: 32
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功