java - 如何在代码中动态添加 Java Agents jar 后卸载它们? Java 检测

标签 java instrumentation agent javaagents

我已经创建了一个 java 代理 jar 文件(在命令行上运行完美)。 接下来,我想将此代理附加到 j2ee 服务器中正在运行的 JVM。 所以我使用了代码:

public static void loadAgent() {   

    System.out.println("dynamically loading javaagent");
    String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
    int p = nameOfRunningVM.indexOf('@');
    String pid = nameOfRunningVM.substring(0, p);

    try {
        VirtualMachine vm = VirtualMachine.attach(pid);
        String jarFilePath = vm.getSystemProperties().getProperty("java.home")+File.separator+"lib"+File.separator+"test-agent-7.jar";            
        vm.loadAgent(jarFilePath, "");
        vm.detach();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

编辑:现在可以正常工作了,我可以看到调用了 Transformer。 我还可以移除变压器并能够调试变压器。

我的问题是:

  • 完成后如何卸载此 java 代理 jar?
  • 是关闭/重启 JVM 的唯一方法吗?
  • jar留在内存中有什么影响吗?

最佳答案

好吧,有几件事需要考虑:

如果加载代理,则加载类。只要相关的类加载器在 Java VM 的内存中,相关的类就会保持加载状态。我不认为你可以轻易地预防/规避。但这应该只是很小的内存开销,您可以通过加载代理来解决。

一些研究表明代理将由 SystemClassLoader 加载,因此无法卸载这些类。

Starting Agents After VM Startup

An implementation may provide a mechanism to start agents sometime after the the VM has started. The details as to how this is initiated are implementation specific but typically the application has already started and its main method has already been invoked. In cases where an implementation supports the starting of agents after the VM has started the following applies: The manifest of the agent JAR must contain the attribute Agent-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static agentmain method. The system class loader ( ClassLoader.getSystemClassLoader) must support a mechanism to add an agent JAR file to the system class path. Link to source

但是,您可以影响的是代理正在做什么。

您想关闭该代理吗?提供关机方法。

如果您想从外部停止代理,该代理可以提供一个 JMXBean 来关闭代理。

此方法然后可以从 Instrumentation 接口(interface)中删除转换器或停止代理在 Java VM 中执行的任何其他操作(释放引用/持有的资源,以便对象被垃圾收集,类似这样的东西)。

如果不更具体地说明您想要实现的目标,就很难给出更合适的答案。

关于java - 如何在代码中动态添加 Java Agents jar 后卸载它们? Java 检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18057504/

相关文章:

visual-studio-2010 - 如何使用 VS 2010 或 VS 2013 分析签名程序集

tomcat - Cobertura仪器类

java - VM 启动后启动 Instrumentation Agent

java - JADE 代理与 WSIG 集成

java - 使用 Apache Commons compress 解压 Tar 文件时发生异常

android - Android Studio 的 Gradle 测试(检测)

java - Android - 禁用 ListView 选择突出显示但保持 OnClick 启用

python - 在用 Python 编写的基于代理的模型中使用 __slots__

java - 如何顺序地为同一类型的事实编写规则?

java - hibernate - 如何在运行时更改属性