在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ 是否有辦法可以從jvm中獲取到對象并調(diào)用方法

是否有辦法可以從jvm中獲取到對象并調(diào)用方法

比如我首先用java命令啟動了一個程序,然后我想在另外一個java程序里,獲取之前那個程序中的對象并調(diào)用相應的方法。

目前能夠做到的是,可以使用jdk提供的工具包tools.jar里的方法,調(diào)用自己寫的java agent

String pid = "xxxx";
HotSpotVirtualMachine vm = (HotSpotVirtualMachine) new LinuxAttachProvider().attachVirtualMachine(pid);
vm.loadAgent(".../testAgent.jar");
vm.detach();

這里的java agent可以拿到類的信息

public class TestAgent {

    public static void agentmain(String args, Instrumentation inst) throws IllegalAccessException, InstantiationException {
        System.out.println("loaded classes: " + inst.getAllLoadedClasses().length);
        System.out.println("================");
        Class[] classes = inst.getInitiatedClasses(TestAgent.class.getClassLoader());
        System.out.println("initiated classes: " + classes.length);
        for (Class clazz: classes) {
            System.out.println(clazz.getName());
        }
        System.out.println("================");
    }

}

但是似乎拿不到當前正在使用的對象或者引用。
請問有辦法可以做到嗎?

回答
編輯回答
遲月

你需要了解下 進程間通信 —— 最為一般的方式是使用 Socket(RPC)

2018年9月5日 16:28
編輯回答
久礙你

明白一點:agentmain函數(shù)是在目標JVM進程中執(zhí)行的。所以很簡單,使用反射就可以調(diào)用目標JVM進程中的類的方法。

    public static void agentmain(String args, Instrumentation instrumentation)
        throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        ...
        // 反射獲取目標類
        Class<?> testTarget = Class.forName("TestTarget");
        // 類實例化
        Object newInstance = testTarget.newInstance();
        // 獲取目標方法
        Method end = testTarget.getDeclaredMethod("end", null);
        // 調(diào)用目標方法
        end.invoke(newInstance, null);
    }
2017年8月15日 21:44