0

Is it possible with ByteBuddy to replace occurences of some type in bytecode? E. g. if I have a class

class MyClass {
    Foo makeFoo() {
       return new Foo(); 
    }
}

I want to transform bytecode of this class so that it is equivalent to

class MyClass {
    Bar makeFoo() {
       return new Bar(); 
    }
}

i. e. replace all occurrences of Foo with Bar.

leventov
  • 14,760
  • 11
  • 69
  • 98
  • 1
    ByteBuddy settles on ASM and provides an easier interface for certain use cases, but I think, replacing occurrences of types is not within these use cases. I would even go so far and consider ASM to be not the best choice for this kind of task, as you could replace all occurrences easily and efficiently by only processing the constant pool of a class, the only operation, ASM does not support directly. – Holger Dec 15 '16 at 11:03

1 Answers1

1

As Holger suggested, this is not within the scope of what Byte Buddy tries to achieve. Byte Buddy attempts offering a safe environment for code manipulations where in your case, it would need to validate that Bar is a valid replacement for Foo. Also, it would need to recompute stack map frames what is rather expensive.

If you want to use Byte Buddy, it offers access to ASM which is underlying. ASM offers Remapper which you can use for such a thing. If you only want to do this, you should probably consider to use ASM without Byte Buddy. As Holger mentions in his comment, the most efficient way would be to rewrite the constant pool entry which is the root reference to Foo which ASM does not support so you might even want to find another way, even though a simple ASM visitation does not generate too much overhead.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192