一、编译脚本
ClassLoader parent =ClassLoader.getSystemClassLoader();
GroovyClassLoader loader =new GroovyClassLoader(parent);
Class<?> clazz = loader.parseClass(codeContent);
ConcurrentHashMap<String, Object> toolMap = new ConcurrentHashMap<>();
toolMap.put(groovyClass.getSimpleName(), groovyClass);
GroovyObject clazzObj =(GroovyObject)clazz.newInstance();
System.out.println(clazzObj.invokeMethod("test","str"));
注意:需要注意的是,通过看groovy的创建类的地方,就能发现,每次执行的时候,都会新生成一个class文件,这样就会导致JVM的perm区持续增长,进而导致FullGCc问题,解决办法很简单,
就是脚本文件变化了之后才去创建文件,之前从缓存中获取即可,缓存的实现可以采用简单的CourrentHashMap或者使用之前文章提到的EhCache(同时可以设置缓存有效期,降低服务器压力)
二、执行
public static Object invokeClass(String className, String methodName, Object... params){
if (StringUtils.isBlank(className) || StringUtils.isBlank(methodName)){
log.error("method name or class name is null!");
return null;
}
Class clz = (Class)GlobalTool.toolMap.get(className);
Method[] methods = clz.getMethods();
for (Method m : methods){
Object result = null;
Method method = null;
if (m.getName().equals(methodName)){
Object o = null;
try {
o = clz.newInstance();
try {
if (m.getParameterCount() == 0 && params.length == 0){
method = clz.getMethod(m.getName());//返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法
try {
result= method.invoke(o);//静态方法第一个参数可为null,第二个参数为实际传参
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}else {
method = clz.getMethod(m.getName(), m.getParameterTypes());//返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法
try {
if (params.length == 0){
log.error("params are illegal!");
return null;
}
if (m.getParameterTypes().length != params.length){
continue;
}else if (m.getParameterTypes().length == params.length){
log.info("method and param combine successful!");
result= method.invoke(o, params);//静态方法第一个参数可为null,第二个参数为实际传参
}
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}else {
continue;
}
return result;
}
return null;
}
原文:https://www.cnblogs.com/yyqxxy/p/12871515.html