byte-buddy icon indicating copy to clipboard operation
byte-buddy copied to clipboard

How to replace final field

Open dep4 opened this issue 6 months ago • 1 comments

Rafael,

I tried to find an answer to this question for a long time but so far only found MemberSubstitution, which replaces access but not the definition. If you could please point me into the right direction?

Replace

class ClassA {
  static final ClassB field=new ClassB(1)
}

with

class ClassA {
  static final ClassB field=new ClassB(2)
}

One use case is to replace field in interface so reflection and setting in construction would not apply there.

I'm saving bytecode to file rather that injecting if that lifts any restrictions. If that's only possible with ASM, is there an approximate example?

Many thanks

dep4 avatar Jun 25 '25 14:06 dep4

You need to match ElementMatchers.isTypeInitializer() as a target. You would then need to match a constructor for ClassB and probably define a replacement chain where you first replace the argument and then invoke the original constructor.

raphw avatar Jun 25 '25 23:06 raphw