java agent如何實作? 1.實作java agent需要實作premain方法;2、必須在MANIFEST.MF檔中有Premain-Class。
在字節碼這個層面對類別和方法進行修改的技術,能夠在不影響編譯的情況下,修改字節碼。可以理解spring的aop技術
在字節碼這個層面對類別和方法進行修改的技術,能夠在不影響編譯的情況下,修改字節碼。可以理解spring的aop技術
實作javaagent需要實作premain方法
package com.xueyou.demo.agent; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.CtNewMethod; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; public class FirstAgent implements ClassFileTransformer { public final String injectedClassName = "com.xueyou.agentdemo.App"; public final String methodName = "hello"; public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { className = className.replace("/", "."); // System.out.println(className); if (className.equals(injectedClassName)) { CtClass ctclass = null; try { ctclass = ClassPool.getDefault().get(className);// 使用全称,用于取得字节码类<使用javassist> CtMethod ctmethod = ctclass.getDeclaredMethod(methodName);// 得到这方法实例 ctmethod.insertBefore("System.out.println(11111111);"); return ctclass.toBytecode(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } return null; } }
package com.xueyou.demo; import com.xueyou.demo.agent.FirstAgent; import java.lang.instrument.Instrumentation; /** * Hello world! */ public class App { public static void premain(String agentOps, Instrumentation inst) { System.out.println("=========premain方法执行========"); System.out.println(agentOps); // 添加Transformer inst.addTransformer(new FirstAgent()); } }
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <manifestEntries> <PremainClass>com.xueyou.demo.App</Premain-Class> </manifestEntries> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build>
1)使用命令列:java -javaagent:XXX.jar ddd.jar
2)使用idea的vm option選項。
以上是如何實作java agent?分享java agent的使用案例的詳細內容。更多資訊請關注PHP中文網其他相關文章!