javaagent 使用以及陷阱

http://www.javamex.com/tutorials/memory/instrumentation.shtml


http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/package-summary.html


范例

定义一个SayHello的agent类


package com.fdd.test.hello;


import java.lang.instrument.Instrumentation;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class SayHello {
private static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
 
public static void premain(String args, Instrumentation inst) throws Exception{
        executor.scheduleAtFixedRate(new PrintHello(), 2000, 2000, TimeUnit.MILLISECONDS);


    }

private static class PrintHello implements Runnable{


@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("new say hello...");
}

}
}


第一个主程序

package com.fdd.test.hello;


public class Main {


public staticvoid main(String[] args) throws Exception{

// TODO Auto-generated method stub

while (true) {

Thread.sleep(1000);

System.out.println("main ....");

}

}

}


编译这两个类

 javac com/fdd/test/hello/SayHello.java

javac com/fdd/test/hello/Main.java


编写manifect文件

manifest.txt 

Premain-Class: com.fdd.test.hello.SayHello


注意:Premain-Class: com.fdd.test.hello.SayHello后面的得换行,否则打到jar的时候,不会把Premain-Class: com.fdd.test.hello.SayHello打进去,,跑不动


将sayhello 的class文件,manifect文件,打到jar里面

jar -cmf manifest.txt agent.jar com/fdd/test/hello/SayHello*.class


最后测试

java -javaagent:/Users/yumo/workspace/test/src/agent.jar com.fdd.test.hello.Main

输出:

main ....  //主程序的输出

new say hello... //代理类的输出

main ....

main ....

new say hello...

main ....

main ....

new say hello...

main ....

main ....

new say hello...

main ....

main ....

new say hello...

main ....



你可能感兴趣的:(Java)