refactor: rm static block for better life

This commit is contained in:
ReaJason
2025-08-13 23:53:40 +08:00
parent 3a10568346
commit 829b0e8be7
52 changed files with 49 additions and 220 deletions
@@ -5,7 +5,7 @@ import net.bytebuddy.dynamic.DynamicType;
import java.lang.reflect.Field;
import static net.bytebuddy.matcher.ElementMatchers.isTypeInitializer;
import static net.bytebuddy.matcher.ElementMatchers.isDefaultConstructor;
/**
* JDK9 引入的 module 系统,只有主动声明 exports 的才能被外部访问。当前用于打破 module 的限制,使我们能像低版本一样任意反射获取方法
@@ -33,24 +33,12 @@ 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 代码
* 值得注意的一点,builder 是不可变类型,所以都是需要重新赋值,例如以下代码示例
* # code that not work
* builder = new Bytebuddy().redefine(class);
* builder.visit(something);
* builder.make();
* <br>
* # code that work
* <br>
* builder = new Bytebuddy().redefine(class);
* builder = builder.visit(something);
* builder.make();
*
* 在默认构造方法中执行 byPassJdkModule 代码
* @param builder bytebuddy builder
* @return new builder with bypass
*/
public static DynamicType.Builder<?> extend(DynamicType.Builder<?> builder) {
return builder.visit(Advice.to(ByPassJavaModuleInterceptor.class)
.on(isTypeInitializer()));
.on(isDefaultConstructor()));
}
}
@@ -0,0 +1,46 @@
package com.reajason.javaweb.buddy;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.jar.asm.MethodVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import static net.bytebuddy.matcher.ElementMatchers.isTypeInitializer;
/**
* 在静态代码块中添加构造方法调用例如:
* static {
* new Injector();
* }
*
* @author ReaJason
* @since 2025/8/12
*/
public class StaticBlockSelfConstructorCall implements ByteCodeAppender {
public static StaticBlockSelfConstructorCall INSTANCE = new StaticBlockSelfConstructorCall();
public static DynamicType.Builder<?> extend(DynamicType.Builder<?> builder) {
return builder
.invokable(isTypeInitializer())
.intercept(new Implementation.Simple(StaticBlockSelfConstructorCall.INSTANCE));
}
@Override
public Size apply(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
MethodDescription instrumentedMethod) {
methodVisitor.visitTypeInsn(Opcodes.NEW, implementationContext.getInstrumentedType().getInternalName());
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL,
implementationContext.getInstrumentedType().getInternalName(),
"<init>",
"()V",
false);
methodVisitor.visitInsn(Opcodes.POP);
methodVisitor.visitInsn(Opcodes.RETURN);
return new Size(2, 2);
}
}