欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Instrumentation-Java代码替换核心接口

程序员文章站 2022-03-27 12:55:57
在java.lang.instrument中对核心类Instrumentation的两种使用方式说明如下*

* There are two ways to obtain an instance of the* Instrumentation interface:**

    *
  1. When a JVM is launched in a way that indicates...

在java.lang.instrument中对核心类Instrumentation的两种使用方法说明如下

* <P>
* There are two ways to obtain an instance of the
* <code>Instrumentation</code> interface:
*
* <ol>
*   <li><p> When a JVM is launched in a way that indicates an agent
*     class. In that case an <code>Instrumentation</code> instance
*     is passed to the <code>premain</code> method of the agent class.
*     </p></li>
*   <li><p> When a JVM provides a mechanism to start agents sometime
*     after the JVM is launched. In that case an <code>Instrumentation</code>
*     instance is passed to the <code>agentmain</code> method of the
*     agent code. </p> </li>
* </ol>
* <p>

两种方法

1、premain方法:JVM启动时使用-javaagent 参数指定一个jar包,jar包的启动类里需要实现下面两个方法里的任意一个。在类被加载前修改字节码,可进行类结构修改如增删方法/成员变量。

public static void premain(String agentArgs, Instrumentation inst); 
public static void premain(String agentArgs); 

  premain详细介绍:https://www.jianshu.com/p/0bbd79661080

  premain用法示例:https://gitee.com/yangkaiwei/premain-agent

 

2、agentmain方法: 在代理类中实现下面方法的任意一个,只能修改方法体,不能修改类结构。可在JVM运行中的任意时刻进行修改,即使类已经被加载。

public static void agentmain (String agentArgs, Instrumentation inst);
public static void agentmain (String agentArgs);

  agentmain详细介绍:https://www.cnblogs.com/stateis0/p/9062201.html

  agentmain用法示例:https://gitee.com/yangkaiwei/hot-swap-tool

 

三、其他相关内容:

  1. JVM Tool Interface(JVMTI),是 JVM 暴露出来的一些供用户扩展的接口集合。JVMTI 是基于事件驱动的,JVM 每执行到一定的逻辑就会调用一些事件的回调接口(如果有的话),这些接口可以供开发者扩展自己的逻辑。它是实现 Java 调试器,以及其它 Java 运行态测试与分析工具的基础。JVMTI 的功能非常丰富,包含了虚拟机中线程、内存 / 堆 / 栈,类 / 方法 / 变量,事件 / 定时器处理等等 20 多类功能。

    https://developer.ibm.com/zh/articles/j-lo-jpda2/

    https://docs.oracle.com/javase/7/docs/platform/jvmti/jvmti.html

  2. JVM Attach机制,jvm提供一种jvm进程间通信的能力,能让一个进程传命令给另外一个进程,并让它执行内部的一些操作,比如内存dump,线程dump,类信息统计(比如加载的类及大小以及实例个数等),动态加载agent(使用过btrace的应该不陌生),相关线程”Attach Listener”和“Signal Dispatcher”。http://lovestblog.cn/blog/2014/06/18/jvm-attach/
  3. Java动态追踪技术探究 --美团技术 https://tech.meituan.com/2019/02/28/java-dynamic-trace.html


 

 

 

 

 

 

 

 

 

本文地址:https://blog.csdn.net/qq_23581569/article/details/110199624