从一体式罐子中附加 Java 代理



我只是想尝试一下javassist,并开始编辑库的方法体。为了挂接到库,我使用位于'%JAVA_HOME%.中的工具.jar附加了一个代理。\lib\'.

但是我不喜欢我在为工具安装jdk时使用的每台PC的想法.jar

难道没有另一种方法可以将罐子的输入提取到我的最后一个罐子中吗?
我用javassist这样做了,它似乎工作得很好(IntelliJ这样做了。它有一个很好的功能 http://puu.sh/hoiCo/bf19853b12.png)
但是使用工具这样做.jar最终会导致程序引发异常

异常 http://puu.sh/hoiGd/844567bca2.png 的屏幕截图

public static void main(String[] args){
    if(args.length < 1){
        log("No ProcessID set");
        return;
    }
    String pid = args[0];
    VirtualMachine vm = null;
    try{
        vm = VirtualMachine.attach(pid);
        String filePath = AgentMain.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        filePath = URLDecoder.decode(filePath, "UTF-8");
        if(filePath.startsWith("/")){
            filePath = filePath.substring(1);
        }
        log("Loading Agent... [" + filePath + "]");
        vm.loadAgent(filePath);
    }catch(Exception ex){
        log("VM connection error [" + pid + "]");
        ex.printStackTrace();
    }finally{
        try{
            if(vm != null) vm.detach();
        }catch(Exception ex){}
    }
}

这是我用于注入代理的代码。

如果有人能帮忙,那就太好了。
希望你明白:)

此项目可能会对您有所帮助: 轨道/代理加载器

public class HelloAgent
{
    public static void agentmain(String agentArgs, Instrumentation inst)
    {
        System.out.println(agentArgs);
        System.out.println("Hi from the agent!");
        System.out.println("I've got instrumentation!: " + inst);
    }
}
public static void main(String[] args)
{
    AgentLoader.loadAgentClass(HelloAgent.class.getName(), "Hello!");
}

它将虚拟机类捆绑在其中,因此您不需要工具 jar 在运行时附加代理。

它在专家身上:

<dependency>
    <groupId>com.ea.orbit</groupId>
    <artifactId>orbit-agent-loader</artifactId>
    <version>0.5.2</version>
</dependency>

应该可以将其与您的应用程序捆绑在一个 jar 中。


从您的评论中不清楚您是否知道这一点,但您也可以使用 VM 选项运行您的程序: -javaagent:your-agent.jar

附带说明:在Intellij中,您可以将java程序和单元测试的默认启动器设置为默认具有-javaagent:something.jar。有趣的是,jar 不需要有实际的代理类,它只需要正确的清单条目。(前提是代理类位于正在运行的项目/模块的类路径中的某个位置)。

最新更新