我有一个具有以下代码的类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
中(。
预先感谢
您需要两个罐子:
-
一个是使用反射来更改场值的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文件中。
-
第二个是使用动态附件将代理JAR注入运行VM的实用程序。令
pid
为目标Java进程ID。import com.sun.tools.attach.VirtualMachine; ... VirtualMachine vm = VirtualMachine.attach(pid); try { vm.loadAgent(agentJarPath, ""); } finally { vm.detach(); }
文章中的更多详细信息。