import net.bytebuddy.ByteBuddy; import net.bytebuddy.implementation.MethodDelegation; import net.bytebuddy.matcher.ElementMatchers; public class DynamicProxyExample { public static void main(String[] args) throws IllegalAccessException, InstantiationException { Class<?> proxyClass = new ByteBuddy() .subclass(Object.class) .method(ElementMatchers.named("toString")) .intercept(MethodDelegation.to(LoggerInterceptor.class)) .make() .load(DynamicProxyExample.class.getClassLoader()) .getLoaded(); Object proxy = proxyClass.newInstance(); System.out.println(proxy.toString()); } } class LoggerInterceptor { public static String toString() { System.out.println("Proxy method interception"); return ""; } } import net.bytebuddy.ByteBuddy; import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy; import net.bytebuddy.implementation.FixedValue; import net.bytebuddy.matcher.ElementMatchers; public class DynamicTestGeneration { public static void main(String[] args) throws IllegalAccessException, InstantiationException { DynamicType.Unloaded<?> dynamicType = new ByteBuddy() .subclass(Object.class) .name("MyTestClass") .annotateType(AnnotationDescription.Builder.ofType(Deprecated.class).build()) .constructor(ConstructorStrategy.Default.IMITATE_SUPER_TYPE) .method(ElementMatchers.named("toString")) .intercept(FixedValue.value("Hello, Byte Buddy!")) .make(); Class<?> testClass = dynamicType.load(DynamicTestGeneration.class.getClassLoader()) .getLoaded(); Object testObject = testClass.newInstance(); System.out.println(testObject.toString()); } }


上一篇:
下一篇:
切换中文