Java Agent初探——動態修改代碼

來源:互聯網
上載者:User

Java Agent初探——動態修改代碼

用了一下午總算把java agent給跑通了,本篇文章記錄一下具體的操作步驟,以免遺忘。。。

通過java agent可以動態修改代碼(替換、修改類的定義),進行AOP。

目標:

為所有添加@ToString註解的類實現預設的toString方法

需要兩個程式,一個是用來測試的程式,一個agent用於修改代碼。1. 測試程式

被測試的程式包括:

- ToString.java

- Foo.java

- Main.java

具體代碼如下:

ToString.java:定義ToString註解

package com.chosen0ne.agent.test;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)public @interface ToString {}

Foo.java:很簡單用於測試,使用了ToString註解

 

 

package com.chosen0ne.agent.test;@ToStringpublic class Foo {}

Main.java:
package com.chosen0ne.agent.test;public class Main {    public static void main(String[] args) {        Foo foo = new Foo();        System.out.println(foo.toString());    }}

執行Main.java,結果如下:
[email protected]
可以看到toString返回的是Object的預設實現。2. Agent程式

java agent程式實際上類似於鉤子,有兩種方式:

- main函數開始前

- 程式運行中

這裡主要測試main函數開始前的情況。類似於main函數,需要實現

public static void premain(String agentArgs, Instrumentation inst);
這個函數會在main函數之前被調用。可以在premain中,進行位元組碼操作,替換或重新實現一些類。這裡使用Byte Buddy庫,在ASM之上提供了更進階的抽象,便於使用。具體代碼如下:
package com.chosen0ne.ByteCode.agent;import java.lang.instrument.Instrumentation;import com.chosen0ne.agent.test.ToString;import net.bytebuddy.agent.builder.AgentBuilder;import net.bytebuddy.description.type.TypeDescription;import net.bytebuddy.dynamic.DynamicType.Builder;import net.bytebuddy.implementation.FixedValue;import net.bytebuddy.matcher.ElementMatchers;public class ToStringAgent {    public static void premain(String args, Instrumentation instrumentation) {        System.out.println("print pre main");        new AgentBuilder.Default()                .type(ElementMatchers.isAnnotatedWith(ToString.class))                .transform(new AgentBuilder.Transformer() {                    @Override                    public Builder transform(Builder builder,                            TypeDescription typeDescription, ClassLoader classLoader) {                        return builder.method(ElementMatchers.named("toString"))                                .intercept(FixedValue.value("test"));                    }                                    }).installOn(instrumentation);    }}
agent需要打包成jar,並且對於premain的方式需要在MANIFEST.MF中指定Premain-Class,用於指明包含premain函數的類。具體有兩種方式打包:

1)直接通過jar命令

編輯產生MANIFEST.MF後,執行:

jar cvfm agent.jar MANIFEST.MF -C . com lib
上述命令打包成的jar包含:

- com:編譯產生的class檔案

- lib:其依賴的庫

2)通過maven直接產生:

通過maven-jar-plugin外掛程式產生jar包,具體配置如下:

<build>    <plugins>            <plugin>            <groupid>org.apache.maven.plugins</groupid>            <artifactid>maven-jar-plugin</artifactid>            <version>2.1</version>            <configuration>                <archive>                    <manifest>                        <addclasspath>true</addclasspath>                        <classpathprefix>lib/</classpathprefix>                        <mainclass>com.chosen0ne.ByteCode.ByteBuddyTest</mainclass>                    </manifest>                    <manifestentries>                        <premain-class>com.chosen0ne.ByteCode.agent.ToStringAgent</premain-class>                    </manifestentries>                </archive>            </configuration>        </plugin>    </plugins></build>
主要通過manifestEntries標籤產生自動的屬性,這裡指定了Premain-Class3. 運行

將產生的agent.jar、依賴的ByteBuddy的jar包和測試程式編譯產生的class檔案放到一個路徑下,目錄布局如下:

.├── agent.jar├── classes│ └── com│     └── chosen0ne│         └── agent│             └── test│                 ├── Foo.class│                 ├── Main.class│                 └── ToString.class└── lib    └── byte-buddy-1.2.3.jar

在目前的目錄執行命令:
java -cp classes:lib/byte-buddy-1.2.3.jar -javaagent:agent.jar com.chosen0ne.agent.test.Main
運行結果如下:
print pre maintest

這裡需要注意一點,如果將測試程式也打包成jar包的話,那麼在通過-cp指定ByteBuddy庫時會失敗,找不到對應的class,錯誤如下:
> java -cp classes:lib/byte-buddy-1.2.3.jar -javaagent:agent.jar -jar agent-test-case-0.0.1-SNAPSHOT.jarException in thread "main" java.lang.NoClassDefFoundError: net/bytebuddy/matcher/ElementMatcherat java.lang.Class.getDeclaredMethods0(Native Method)at java.lang.Class.privateGetDeclaredMethods(Class.java:2688)at java.lang.Class.getDeclaredMethod(Class.java:2115)at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:327)at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)Caused by: java.lang.ClassNotFoundException: net.bytebuddy.matcher.ElementMatcherat java.net.URLClassLoader$1.run(URLClassLoader.java:372)at java.net.URLClassLoader$1.run(URLClassLoader.java:361)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(URLClassLoader.java:360)at java.lang.ClassLoader.loadClass(ClassLoader.java:424)at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)at java.lang.ClassLoader.loadClass(ClassLoader.java:357)... 5 moreFATAL ERROR in native method: processing of -javaagent failed
暫時不知道具體原因。。。所以直接以class運行即可

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.