java程序启动后,在不终止进程的情况下,如何向jvm内动态的添加java类呢?办法如下:
1、增加如下依赖
<!-- 动态编译 -->
<dependency>
<groupId>org.noear</groupId>
<artifactId>liquor-eval</artifactId> <!-- or liquor -->
<version>1.6.5</version>
</dependency>
<dependency>
<groupId>org.noear</groupId>
<artifactId>solon</artifactId>
<version>3.3.3</version>
</dependency>
2、写个测试
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import org.noear.liquor.DynamicCompiler;
import org.noear.solon.core.util.ResourceUtil;
//import org.springframework.boot.test.context.SpringBootTest;
//@SpringBootTest
public class CompilerTest {
@Test
public void test() throws Exception {
CompilerTest.compilerString();
CompilerTest.compilerFile();
}
public static void compilerString() throws Exception {
String className = "HelloWorld";
String classCode = "public class HelloWorld { " + " public static void helloWorld() { "
+ " System.out.println(\"Hello, world!\"); " + " } " + "}";
DynamicCompiler compiler = new DynamicCompiler();
// 添加源码(可多个)并构建
compiler.addSource(className, classCode).build();
Class<?> clazz = compiler.getClassLoader().loadClass(className);
clazz.getMethod("helloWorld").invoke(null);
classCode = "public class HelloWorld { " + " public static void helloWorld() { "
+ " System.out.println(\"Hello, world 哈哈哈!\"); " + " } " + "}";
compiler = new DynamicCompiler();
// 添加源码(可多个)并构建
compiler.addSource(className, classCode).build();
clazz = compiler.getClassLoader().loadClass(className);
clazz.getMethod("helloWorld").invoke(null);
}
public static void compilerFile() throws Exception {
String className = "com.prostiger.agents.GroovyAgent";
String classCode = ResourceUtil.getResourceAsString("GroovyAgent.txt", null);
System.out.println(classCode);
DynamicCompiler compiler = new DynamicCompiler();
compiler.addSource(className, classCode).build();
Class<?> clazz = compiler.getClassLoader().loadClass(className);
System.out.println(clazz);
for(Method m : clazz.getMethods()) {
for(Annotation a : m.getAnnotations()) {
System.out.println("方法注解:" + a.annotationType().getName());
}
for(java.lang.reflect.Parameter p : m.getParameters()) {
for(Annotation a : p.getDeclaredAnnotations()) {
System.out.println("参数注解:" + a.annotationType().getName());
}
}
}
}
}
参考:
http://solon.noear.org/article/liquor
https://gitee.com/noear/liquor
LoveCTO

