假设我们有一个简单的 Java 程序,它只包含一个类:
public class HelloWorld {
private static void replacable(int i) {
System.out.println("Today is a nice day with a number " + i);
}
public static void main(String[] args) throws Exception {
for(int i = 0; i < 100000; ++i) {
replacable(i);
Thread.sleep(500);
}
}
编译运行后,输出如下:
Today is a nice day with a number 0
Today is a nice day with a number 1
Today is a nice day with a number 2
Today is a nice day with a number 3
...
我的问题:是否存在(或即将出现)某种方式在运行时交换 replacable
方法?类似于用新版本的 replacable
编写另一个版本的 HelloWorld
,编译它,然后在已经运行的 JVM 中编译旧版本?
所以,如果我这样写新版本:
private static void replacable(int i) {
System.out.println("Today is an even nicer day with a number " + i);
}
是否有类似于 Erlang's hot code swapping 的内容?我可以在哪里这样做:
- 运行原程序
- 编写修改版本
- 使用命令行程序,连接到正在运行的 JVM 并替换现有方法
这样,在运行时,就会发生这种情况:
Today is a nice day with a number 15000
Today is a nice day with a number 15001
Today is an even nicer day with a number 15002
Today is an even nicer day with a number 15003
...
假设上述程序是独立的,运行在标准的 Java SE 环境中,类路径上没有其他内容,所以它几乎是一个 Hello world 风格的程序。
注意:我知道字节码操作 (cglib)、aspectJ 等技术, jRebel , JMX ,Java EE等中的方法热交换存在,但它们不是我所想的。想想 Erlang。
最佳答案
您可以使用开源 HotSpot VM或商业广告JRebel IDE插件,轻松实现您的目标(查看比较表here)。
关于java - 通过热交换机制在运行时更改方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4553353/