如何从另一个JVM设置/获取值



我有一个具有以下代码的类Normal

public class Normal {
    private static String myStr = "Not working...";
    private static boolean running = true;
    public static void main(String[] args) {
        while(running) {
            System.out.println(myStr);
        }
    }
}

我在另一个项目中有另一个名为Injector的类。它的目的是更改Normal的值,即使它们不在同一JVM中:

public class Injector {
    public static void main(String[] args) {
    String PID = //Gets PID, which works fine
    VirtualMachine vm = VirtualMachine.attach(PID);
    /*
    Set/Get field values for classes in vm?
    */
    }
}

我要做的是将myStr中的CC_4和running的值分别更改为"Working!"false,而无需更改Normal中的代码(仅在Injector中(。

预先感谢

您需要两个罐子:

  1. 一个是使用反射来更改场值的Java代理。Java代理的主要类应具有agentmain入口点。

    public static void agentmain(String args, Instrumentation instr) throws Exception {
        Class normalClass = Class.forName("Normal");
        Field myStrField = normalClass.getDeclaredField("myStr");
        myStrField.setAccessible(true);
        myStrField.set(null, "Working!");
    }
    

    您必须使用Agent-Class属性添加MANIFEST.MF并将代理打包到JAR文件中。

  1. 第二个是使用动态附件将代理JAR注入运行VM的实用程序。令pid为目标Java进程ID。

    import com.sun.tools.attach.VirtualMachine;
    ...
        VirtualMachine vm = VirtualMachine.attach(pid);
        try {
            vm.loadAgent(agentJarPath, "");
        } finally {
            vm.detach();
        }
    

    文章中的更多详细信息。

最新更新