2017-03-04 295 views
1

请问homebody能给我一个提示如何用byte-buddy 1.6.9重新定义静态方法吗?用ByteBuddy重新定义静态方法

我已经试过这样:

public class Source { 
    public static String hello(String name) {return null;} 
} 


public class Target { 
    public static String hello(String name) { 
     return "Hello" + name+ "!"; 
    } 
} 
String helloWorld = new ByteBuddy() 
       .redefine(Source.class)    
       .method(named("hello")) 
       .intercept(MethodDelegation.to(Target.class)) 
       .make() 
       .load(getClass().getClassLoader()) 
       .getLoaded() 
       .newInstance() 
       .hello("World"); 

我得到了以下异常:

异常线程 “main” java.lang.IllegalStateException:不能注入已经加载类型:类delegation.Source

谢谢

回答

0

类只能由每个类加载器加载一次。为了替换方法,您需要使用Java代理来挂接JVM的HotSwap功能。

字节好友提供了使用这种试剂,使用一个类加载策略:

.load(Source.class.getClassLoader(), 
     ClassReloadingStrategy.fromInstalledAgent()); 

但这不过需要你安装一个Java代理。在JDK上,可以通过编程方式执行ByteBuddyAgent.install()(包含在字节伙伴代理工件中)。在JVM上,您必须在命令行上指定代理。

+0

Rafael,如果我想重新定义Target类的重新定义的方法中Source类的hello()静态方法,我仍然可以调用Source类的原始静态方法吗?非常感谢 ! –

+0

查看'Advice'类,您可以在原始方法之前和之后添加代码,并且还可以有条件地跳过该方法。除此之外,您只能重新绑定类以保留原始实现。 –

+0

您是否知道有关如何使用Advice类的任何示例?谢谢 ! –