字节码增强-动态改变类信息

废话不多说 直接上代码,如下是修改或者增加RpcFilter实现类上Order注解

程序加载该类前执行代码,如spring可以在org.springframework.boot.SpringApplicationRunListener的contextLoaded方法中

        try {
            //默认的类搜索路径
            ClassPool pool = ClassPool.getDefault();
            CtClass ctClass = pool.get(XXXServerFilter.class.getName());
            ClassFile classFile = ctClass.getClassFile();
            AnnotationsAttribute attributeInfo = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
            Annotation annotation = new Annotation(Order.class.getName(), classFile.getConstPool());
            MemberValue memberValue = new IntegerMemberValue(classFile.getConstPool(), Integer.MAX_VALUE - 1);
            annotation.addMemberValue("value", memberValue);
            attributeInfo.addAnnotation(annotation);
            classFile.addAttribute(attributeInfo);
            reTransformClass(SatelliteHSFServerFilter.class, ctClass.toBytecode());
        } catch (Exception e) {
            LogUtils.warn(e, "SpringApplicationRunListener.contextLoaded", Maps.newHashMap());
        }
    private static void reTransformClass(Class<?> clazz, byte[] byteCode) {
        ClassFileTransformer cft = (loader, className, classBeingRedefined, protectionDomain, classfileBuffer) -> byteCode;

        Instrumentation instrumentation = ByteBuddyAgent.install();
        try {
            instrumentation.addTransformer(cft, true);
            instrumentation.retransformClasses(clazz);
        } catch (UnmodifiableClassException e) {
            e.printStackTrace();
            LogUtils.warn(e,"SpringApplicationRunListener.reTransformClass", Maps.newHashMap());
        } finally {
            instrumentation.removeTransformer(cft);
        }
    }

引入包
byte-buddy

<dependency>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy-agent</artifactId>
    <version>1.14.2</version>
</dependency>

javassist

 <dependency>
 	<groupId>org.javassist</groupId>
  	<artifactId>javassist</artifactId>
  	<version>3.21.0-GA</version>
 </dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值