77import net .bytebuddy .dynamic .DynamicType ;
88import net .bytebuddy .implementation .FixedValue ;
99import net .bytebuddy .implementation .MethodCall ;
10- import net .bytebuddy .implementation .bytecode .assign .Assigner ;
1110
1211import java .lang .reflect .Field ;
1312
2019 * @author ReaJason
2120 */
2221public class ByPassJdkModuleInterceptor {
23- @ Advice .OnMethodExit
24- public static void enter (@ Advice .Origin Class <?> clazz , @ Advice . Return ( readOnly = false , typing = Assigner . Typing . DYNAMIC ) boolean returnValue ) {
22+ @ Advice .OnMethodEnter
23+ public static void enter (@ Advice .Origin Class <?> clazz ) {
2524 try {
2625 Class <?> unsafeClass = Class .forName ("sun.misc.Unsafe" );
2726 java .lang .reflect .Field unsafeField = unsafeClass .getDeclaredField ("theUnsafe" );
@@ -32,7 +31,6 @@ public static void enter(@Advice.Origin Class<?> clazz, @Advice.Return(readOnly
3231 Long offset = (Long ) objectFieldOffsetM .invoke (unsafe , Class .class .getDeclaredField ("module" ));
3332 java .lang .reflect .Method getAndSetObjectM = unsafe .getClass ().getMethod ("getAndSetObject" , Object .class , long .class , Object .class );
3433 getAndSetObjectM .invoke (unsafe , clazz , offset , module );
35- returnValue = true ;
3634 } catch (Exception ignored ) {
3735 }
3836 }
@@ -41,7 +39,7 @@ public static void enter(@Advice.Origin Class<?> clazz, @Advice.Return(readOnly
4139 * Reference1: <a href="https://stackoverflow.com/questions/62664427/can-i-create-a-bytebuddy-instrumented-type-with-a-private-static-final-methodhan">stackoverflow</a>
4240 * Reference2: <a href="https://github.com/raphw/byte-buddy/issues/1153">issue</a>
4341 * <br>
44- * 向类中添加 byPassJdkModule 方法,并在创建静态变量初始化,使其能在静态代码块中执行 byPassJdkModule 方法
42+ * 向类中添加 byPassJdkModule 方法,并在静态代码块中执行 byPassJdkModule 方法
4543 * 值得注意的一点,builder 是不可变类型,所以都是需要重新赋值,例如以下代码示例
4644 * # code that not work
4745 * builder = new Bytebuddy().redefine(class);
@@ -59,13 +57,12 @@ public static void enter(@Advice.Origin Class<?> clazz, @Advice.Return(readOnly
5957 */
6058 public static DynamicType .Builder <?> extend (DynamicType .Builder <?> builder ) {
6159 return builder
62- .defineField ("isBypassModule" , boolean .class , Visibility .PUBLIC , Ownership .STATIC )
63- .invokable (isTypeInitializer ())
64- .intercept (MethodCall .invoke (named ("byPassJdkModule" )))
65- .defineMethod ("byPassJdkModule" , Object .class , Visibility .PUBLIC , Ownership .STATIC )
66- .intercept (FixedValue .value (false ))
60+ .defineMethod ("byPassJdkModule" , void .class , Visibility .PUBLIC , Ownership .STATIC )
61+ .intercept (FixedValue .originType ())
6762 .visit (new AsmVisitorWrapper .ForDeclaredMethods ()
6863 .method (named ("byPassJdkModule" ),
69- Advice .to (ByPassJdkModuleInterceptor .class )));
64+ Advice .to (ByPassJdkModuleInterceptor .class )))
65+ .invokable (isTypeInitializer ())
66+ .intercept (MethodCall .invoke (named ("byPassJdkModule" )));
7067 }
7168}
0 commit comments