有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用bytebuddy重新定义类

我想重新定义已经在现有框架中定义的源类。我想用我的增强类自动替换源类的原始实例。我无法访问创建源对象的代码,因此类替换必须在后台自动执行。有没有可能使用字节好友来实现这一点

    ByteBuddyAgent.install();
    Source source = new ByteBuddy()
            .subclass(Source.class)
            .method(named("hello")).intercept(MethodDelegation.to(Target.class))
            .defineMethod("myNewMethod", void.class).intercept(MethodDelegation.to(Target.class))
            .make()
            .load(Source.class.getClassLoader(),
                    ClassReloadingStrategy.fromInstalledAgent())
            .getLoaded()
            .newInstance();

共 (1) 个答案

  1. # 1 楼答案

    可以使用Byte Buddy重新定义类。为此,可以使用ByteBuddy::redefineByteBuddy::rebase方法,而不是子类化。使用这些特性的最规范的方法是为AgentBuilder定义一个Java代理