Replacing a method call in a class at runtime

2019-04-11 12:57发布

问题:

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?

回答1:

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.



回答2:

Sounds like you should have a look at JRebel.



标签: java fitnesse