fix: byPassModule not work

This commit is contained in:
ReaJason
2024-12-14 16:26:03 +08:00
parent acfa63c83b
commit 800932118e
@@ -1,17 +1,11 @@
package com.reajason.javaweb.buddy;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.modifier.Ownership;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.MethodCall;
import java.lang.reflect.Field;
import static net.bytebuddy.matcher.ElementMatchers.isTypeInitializer;
import static net.bytebuddy.matcher.ElementMatchers.named;
/**
* JDK9 引入的 module 系统,只有主动声明 exports 的才能被外部访问。当前用于打破 module 的限制,使我们能像低版本一样任意反射获取方法
@@ -39,7 +33,7 @@ public class ByPassJavaModuleInterceptor {
* Reference1: <a href="https://stackoverflow.com/questions/62664427/can-i-create-a-bytebuddy-instrumented-type-with-a-private-static-final-methodhan">stackoverflow</a>
* Reference2: <a href="https://github.com/raphw/byte-buddy/issues/1153">issue</a>
* <br>
* 向类中添加 byPassJdkModule 方法,并在静态代码块中执行 byPassJdkModule 方法
* 在静态代码块中执行 byPassJdkModule 代码
* 值得注意的一点,builder 是不可变类型,所以都是需要重新赋值,例如以下代码示例
* # code that not work
* builder = new Bytebuddy().redefine(class);
@@ -56,13 +50,7 @@ public class ByPassJavaModuleInterceptor {
* @return new builder with bypass
*/
public static DynamicType.Builder<?> extend(DynamicType.Builder<?> builder) {
return builder
.defineMethod("byPassJdkModule", void.class, Visibility.PUBLIC, Ownership.STATIC)
.intercept(FixedValue.originType())
.visit(new AsmVisitorWrapper.ForDeclaredMethods()
.method(named("byPassJdkModule"),
Advice.to(ByPassJavaModuleInterceptor.class)))
.invokable(isTypeInitializer())
.intercept(MethodCall.invoke(named("byPassJdkModule")));
return builder.visit(Advice.to(ByPassJavaModuleInterceptor.class)
.on(isTypeInitializer()));
}
}