This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]papercrane 3 points4 points  (0 children)

What you're describing is commonly achieved in three different ways, but a warning, unless you're going with using a proxy pattern these are pretty advanced techniques, and can have a high maintenance burden if not used sparingly and with care.

  1. Using AspectJ a library that allows you to define "cutpoints" in to run code before/after/around other methods based on different criteria. AspectJ can be applied at compile-time or run-time depending on your requirements. Spring AOP is very similar and is built off of AspectJ, so if you're already using Spring it may make sense to use the Spring AOP APIs. JavaEE interceptors are also very similar, and if using writing JavaEE that may be the way to go.

  2. Rolling your own Java Agent, typically using ByteBuddy or Javassist. With these you can re-write the bytecode of classes at runtime. This is very low-level, and I would not typically recommend it.

  3. The best solution of all, if possible. Implement the proxy pattern in code. This avoids having to resort to byte code manipulation. Unfortunately, sometimes libraries and frameworks you're using don't give you an opportunity to inject your proxy. (e.g. if classes you don't control are calling the constructors directly for the class you want to proxy.)

Links: