Agent agentmain-运行期恢复类修改,热替换

前文讲过运行期修改类,但是有的时候想去除以前的修改,比如曾经添加了类监控,但是现在不想监控了,希望恢复成原生代码。

使用以下代码,重新从源码文件中读取类信息,然后加载到jvm中。

这既可以擦除原来的修改,也可以实现热替换功能。 这里只贴出了关键代码,其它部分和前文一致。

public class RestoreTransformer implements ClassFileTransformer {
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        try {
            if (className.contains(UdAgent.paths));
                return readStream(ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + ".class"), true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static byte[] readStream(InputStream inputStream, boolean close) throws IOException {
        if(inputStream == null) {
            throw new IOException("Class not found");
        } else {
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] data = new byte[4096];

                int bytesRead;
                while((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
                    outputStream.write(data, 0, bytesRead);
                }

                outputStream.flush();
                byte[] var5 = outputStream.toByteArray();
                return var5;
            } finally {
                if(close) {
                    inputStream.close();
                }

            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ljz2016/article/details/84334636