在运行时替换类中的方法调用 [英] Replacing a method call in a class at runtime

查看:119
本文介绍了在运行时替换类中的方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我正在使用fitnesse运行一些自动化测试。有一个名为TableTable的类,如果增强它将允许我做一些很酷的事情。我需要做的是改变这个类的方法 appendInstructions()



因为fitnesse显式查找TableTable类,所以我不能简单地使用我所需的增强功能创建TableTable的子类 - 我无法使fitnesse查找并使用我的自定义子类。 / p>

我当前的解决方案

我采用的临时解决方案是我借用了TableTable的源代码,添加了它在我的源代码树下,与fitnesse的jar下相同的包,并且已经改变了它的代码以满足我的需要。我的代码的类文件出现在类路径中fitnesse的jar之前,所以我的更改被拾取。



我正在尝试做什么

而不是完全遮蔽fitnesse jar中的TableTable类,我想在运行时只重写该类的一个方法。是否有任何代码生成库(如cglib)帮助我在运行时重写类并帮助我实现这一目标?

解决方案

取决于具体方式您需要进行更改,您可以使用 Javassist 修改相关方法的主体。有一个关于使用Javassist拦截/替换方法的教程此处


The problem
I'm using fitnesse for running some automated tests. There is a class called TableTable, which if enhanced would allow me to do some cool things. What I need to do is change what the method appendInstructions() of this class does.

Because fitnesse explicitly looks for TableTable class, I cannot simply create a child class of TableTable with my required enhancements - I cannot make fitnesse find and use my custom child class.

My current solution
The temporary solution I've adopted is I've borrowed the source code of TableTable, added it to my source tree under the same package as it is under in fitnesse's jar, and have changed its code to suit my needs. My code's class files appear before fitnesse's jar in the classpath, so my changes get picked up.

What I'm trying to do
Instead of entirely shadowing the TableTable class in fitnesse's jar, I want to rewrite just the one method of that class at runtime. Will any code generation library (like cglib) help me rewrite the class at runtime and help me achieve this?

解决方案

Depending on how extensive you need the changes to be, you might be able to use Javassist to modify the body of the method in question. There is a tutorial on intercepting/replacing methods using Javassist here.

这篇关于在运行时替换类中的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆