ByteBuddy - rebase already loaded class

ASK:

I have the following code working in a SpringBoot application, and it does what's I'm expecting.

TypePool typePool = TypePool.Default.ofClassPath();
ByteBuddyAgent.install();
new ByteBuddy()
        .rebase(typePool.describe("com.foo.Bar").resolve(), ClassFileLocator.ForClassLoader.ofClassPath())
        .implement(typePool.describe("com.foo.SomeInterface").resolve())
        .make()
        .load(ClassLoader.getSystemClassLoader());

Its makes is so that the class com.foo.Bar implements the interface com.foo.SomeInterface (which has a default implementation)

I would like to . use the above code by referring to the class as Bar.class, not using the string representation of the name. But if I do that I get the following exception.

java.lang.UnsupportedOperationException: class redefinition failed: attempted to change superclass or interfaces

I believe due to the fact that it cause the class to be loaded, prior to the redefinition. I'm just now learning to use ByteBuddy.

I want to avoid some reflection at runtime, by adding the interface and an implementation using ByteBuddy. I've some other code that checks for this interface.

Answer:

This is impossible, not because of Byte Buddy but no tool is allowed to do this on a regular VM. (There is the so-called dynamic code evolution VM which is capable of that).

If you want to avoid the problem, use redefine rather then rebase. Whenever you instrument a method, you do now however replace the original.

If this is not acceptable, have a look at the Advice class which you can use by the .visit-API to wrap logic around your original code without replacing it.

Reply:

this is what my understanding was after reviewing the docs and a couple of similar questions.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值