Java查看动态代理生成的代码 in Action

参考:http://www.cnblogs.com/ctgulong/p/5011614.html

本文纯实践记录:

1、编写自定义javaagent 实现

package common;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

/**
 * javaagent 导出ClassLoader load的class(包括动态生成的class)
 *
 * @author yangpan3
 * @create 2016-07-04 18:38
 */
public class CustomAgent implements ClassFileTransformer {

	// 必须包含premain 方法(虽然ClassFileTransformer并没有声明该方法)
    public static void premain(String agentArgs, Instrumentation inst) {
        inst.addTransformer(new CustomAgent());
    }

    @Override
    public byte[] transform(ClassLoader loader, String className, Class
   
    classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        if (!className.startsWith("java") && !className.startsWith("sun")) {
            String fileName = className.substring(className.indexOf("/") + 1) + ".class";
            exportClazzToFile("D:/experiment/bytecode/export/", fileName, classfileBuffer);
            System.out.println("--CustomAgent.transform() : className = " + className);
        }

        return classfileBuffer;
    }

    private void exportClazzToFile(String path, String fileName, byte[] bytes) {
        File file = new File(path, fileName);
        try {
            File parentFile = file.getParentFile();
            parentFile.mkdirs();
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
2、编译并打包

@echo off

javac -d . CustomAgent.java
@rem CustomAgent 打包为指定jar
jar cvfm agent.jar MANIFEST.MF commonManifest-Version: 1.0
Premain-Class: common.CustomAgent
Created-By: 1.6.0_30 (Sun Microsystems Inc.)
3、Run/Debug JVM Options:

-javaagent:D:\experiment\bytecode\agent.jar

4、cd D:/experiment/bytecode/export/ 查看生成的动态代理class


另外,NB的JRebel 也是javaagent 实现的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值