3

I am trying to wrap my head around this concept. My questions are:

  1. Is this operation costly from a performance point of view, and if so, why?
  2. If I am trying to intercept some parameters being passed to a method by injecting some code after the method is called, does this injection happen once or does it happen every time the method is called?
  3. Where does this injection code reside? In the application source itself or somewhere else?
Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
Mike G
  • 4,829
  • 11
  • 47
  • 76

1 Answers1

9

You can achieve bytecode injection with Java Agents.

A java Agent is a library that intercepts the bytecode loading at the classloader, and enhances it before it is loaded in the JVM. Of course, such a library usually relies on bytecode manipulation librairies such as Javassist, ASM or CGLib. So the bytecode manipulation is only done once, when the class is loaded.

See the official Javadoc : http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html

This article explains how to do pretty much what you want to: http://today.java.net/pub/a/today/2008/04/24/add-logging-at-class-load-time-with-instrumentation.html

Also, if you're really interested in bytecode fundamentals, this article from one of the JRebel developers should please you: http://arhipov.blogspot.com/2011/01/java-bytecode-fundamentals.html

Finally, you can take a look at Seren, a librairy I just began to write. It is a Java Agent that enhances serializable classes. It's just the beginning, but it works. https://github.com/oliviercroisier/seren

Olivier Croisier
  • 6,139
  • 25
  • 34
  • Thanks for the answer but you still didn't provide an answer for the three questions. – Mike G Dec 13 '11 at 17:13
  • 3
    Sorry, here are some more explanations. 1: no performance penalty, it's pure bytecode (no proxy). 2: It happens only once, at class loading, see above. 3: The agent code is in a jar that you must provide on the command line (-javaagent vm parameter); the generated code lives with the rest of the "normal" code, in the PermGen space on the heap. – Olivier Croisier Dec 13 '11 at 17:19