bytebuddy demo
This commit is contained in:
parent
6ea438e5f7
commit
9d36ad9121
|
|
@ -0,0 +1,56 @@
|
|||
package io.github.kazusa.pressmonster.bytebuddy;
|
||||
|
||||
import net.bytebuddy.ByteBuddy;
|
||||
import net.bytebuddy.dynamic.DynamicType;
|
||||
import net.bytebuddy.implementation.FixedValue;
|
||||
import net.bytebuddy.matcher.ElementMatchers;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author Wen
|
||||
* @date 2025/7/22 13:27
|
||||
*/
|
||||
public class HelloWorld {
|
||||
|
||||
@Test
|
||||
public void helloWorld() throws InstantiationException, IllegalAccessException {
|
||||
String helloWorld = new ByteBuddy()
|
||||
// 创建一个Object子类
|
||||
.subclass(Object.class)
|
||||
// 拦截toString方法
|
||||
.method(ElementMatchers.named("toString"))
|
||||
// 指定了拦截到的方法要修改成什么样子
|
||||
.intercept(FixedValue.value("Hello World!"))
|
||||
// 生成字节码
|
||||
.make()
|
||||
// 将生成的字节码加载到JVM中
|
||||
.load(getClass().getClassLoader())
|
||||
// 获取生成的类
|
||||
.getLoaded()
|
||||
.newInstance()
|
||||
.toString();
|
||||
|
||||
System.out.println(helloWorld); // Hello World!
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkClass() throws InstantiationException, IllegalAccessException, IOException {
|
||||
DynamicType.Unloaded<Object> dynamicType = new ByteBuddy()
|
||||
// 创建一个Object子类
|
||||
.subclass(Object.class)
|
||||
.name("io.github.kazusa.pressmonster.bytebuddy.ByteBuddyHelloWorld")
|
||||
// 拦截toString方法
|
||||
.method(ElementMatchers.named("toString"))
|
||||
// 指定了拦截到的方法要修改成什么样子
|
||||
.intercept(FixedValue.value("Hello World!"))
|
||||
// 生成字节码
|
||||
.make();
|
||||
DynamicType.Loaded<Object> load = dynamicType.load(getClass().getClassLoader());
|
||||
dynamicType.saveIn(new File(getClass().getResource("/").getPath()));
|
||||
|
||||
System.out.println(load.getLoaded().newInstance()); // Hello World!
|
||||
}
|
||||
}
|
||||
|
|
@ -9,7 +9,11 @@ import org.springframework.web.bind.annotation.RestController;
|
|||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* RestController插件测试
|
||||
|
|
|
|||
Loading…
Reference in New Issue