raphw / byte-buddy

Runtime code generation for the Java virtual machine.
https://bytebuddy.net
Apache License 2.0
6.29k stars 807 forks source link

Hot to change the argument's field #1565

Closed twogoods closed 11 months ago

twogoods commented 11 months ago
    @Advice.OnMethodEnter(suppress = Throwable.class)
    public static void call(@Advice.Argument(value = 0, readOnly = false) A a) {
        // class A has a private field b, I want change b
        // a.b = xxx  
        // class A no get/set method,origin method at the same package with A, so origin code can use a.b

         Field f = a.getClass().getDeclaredField("b");
         f.setAccessible(true);
         f.set(a, xxx);
         // has other way?
    }
raphw commented 11 months ago

There's no valid byte code instruction that could do that, therefor you need to fall back to reflection or using handles.