feat: 优化编译,更加稳定

This commit is contained in:
wangyu 2022-10-04 22:51:10 +08:00
parent 040452e066
commit b41f0f5ae8

View File

@ -12,6 +12,7 @@ import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -22,6 +23,9 @@ import java.util.stream.Collectors;
*/
public class TemplateCompiler {
// 变量池缓存
private static final Map<Class<?>, Map<String, Method>> POOL_CACHE = new ConcurrentHashMap<>();
/**
* 编译模板文件和源码数据为源代码字符串
*
@ -29,19 +33,18 @@ public class TemplateCompiler {
* @param filename 文件名
* @return 结果
*/
public static Function<JavaSource, String> compile(Class<?> dataClass, String filename) {
public static <T> Function<T, String> compile(Class<T> dataClass, String filename) {
// 获取文件内容
InputStream fis = TemplateCompiler.class.getResourceAsStream(filename);
try {
// 获取模板内容
String template = StreamUtils.copyToString(fis, StandardCharsets.UTF_8);
// 准备变量池
Map<String, PropertyDescriptor> pool = Arrays.stream(BeanUtils.getPropertyDescriptors(dataClass))
.collect(Collectors.toMap(descriptor -> "#{" + descriptor.getName() + "}", a -> a));
Map<String, Method> pool = methodPool(dataClass);
// 编译
return cfg -> pool.keySet().stream().reduce(template, (result, key) -> {
// 获取读取方法
Method method = pool.get(key).getReadMethod();
Method method = pool.get(key);
Object value = null;
try {
// 取得结果
@ -57,6 +60,17 @@ public class TemplateCompiler {
}
}
/**
* 数据类方法池
*
* @param dataClass 数据类
* @return 结果
*/
private static Map<String, Method> methodPool(Class<?> dataClass) {
return POOL_CACHE.computeIfAbsent(dataClass, k -> Arrays.stream(BeanUtils.getPropertyDescriptors(k))
.collect(Collectors.toMap(descriptor -> "#{" + descriptor.getName() + "}", PropertyDescriptor::getReadMethod)));
}
/**
* 解析单个值
*