游戏版本更新没个星期都要进行更新,每次都更新都要在夜深人静的时候进行,这样才能影响到最少的玩家。但是有时候线上出了一些小bug,停服维护又不值得,所以如果可以进行热更新,不停服解决问题,那样就完美了。
我这里用到的也是 java.lang.instrument ,关于这个介绍网上有很多,就不介绍了,直接来说我们的例子。
1、这里是我们的测试用的程序,主要就是循环打印出一个数字,然后我们通过热更新来更改输出的数字。
package com.wynter;
public class TestMain {
public static void main(String[] args) {
while (true) {
try {
Thread.sleep(1000);
Rand rand = new Rand();
System.out.println(rand.getNum());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.wynter;
public class Rand {
public int getNum(){
return 9;
}
}
2、然后我们来看代理类的代码
package com.wynter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
public class Transformer implements ClassFileTransformer {
public static final String classNumberReturns2 = "/root/cssg/com/wynter/hotclass/Rand.class.2";
public static byte[] getBytesFromFile(String fileName) {
try {
// precondition
File file = new File(fileName);
InputStream is = new FileInputStream(file);
long length = file.length();
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;