Question

a colleague pointed me the other day to BCEL which , as best I can tell from his explanation and a quick read, a way to modify at run time the byte code. My first thought was that it sounded dangerous, and my second thought was that it sounded cool. Then I gave it some more thought and I recalled the codinghorror post on monkey-patching and realized that this was basically the same thing. Has anyone ever used BCEL for anything practical? Am I right that this is basically run time monkey patching, or am I missing something?

Was it helpful?

Solution

It's a bit more low-level than classic monkey patching, and from what I read, the classes already loaded into the VM are not updated. It only supports saving it to class files again, not modifying run time classes.

OTHER TIPS

From BCEL's FAQ:

Q: Can I create or modify classes dynamically with BCEL?

A: BCEL contains useful classes in the util package, namely ClassLoader and JavaWrapper.Take a look at the ProxyCreator example.

But monkeypatching is... uhm... controversial, and you probably shouldn't use it if your language doesn't support it.

If you have a good use case for it, may I suggest embbededing Jython?

You might look at it as monkey patching. I prefer not to use it (maybe I never faced a good use case for it?), but be familiar with it (to have an idea how Spring and Hibenrate use it and why).

See this realworld example: Jawk - Compiler Module. BCEL is useful for "compilation" ur custom language.

BCEL does not support monkey patching, it just manipulates with bytecode and possibly loads it in a custom classloader. However you can implement monkeypatching on JVM using library like BCEL and Java agent. The Java agent (loaded by -javaagent argument) can access the Instrumentation API and modify loaded classes. It is not hard to implement it via some bridges.

But remember:

  • I am not sure if having to use -javaagent is something you want.
  • In any language, monkey patching can lead to badly predictable behavior.
  • You can modify a method. In theory, you can also add some method, but you need to compile the project against modified (patched) classes. I think this would cause a lot of pain and it is not worth of it. There are alternative languages that support it (e.g. Groovy) or suppport something similar (e.g. implicit conversions in Scala).
  • It is better to design your API well than to use monkey patching. It may be rather useful for third party libraries.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top