2

I have a quite large codebase. In many places I have a piece of code like this:

for (MyObjectType myobj : myList) {
   //...do something with myobj
}

MyObjectType is the basic object in my application, and I iterate over many of them very often. I have some log4j set up so that I log info about the MyObjectType instance I am dealing with:

for (MyObjectType myobj : myList) {
   MDC.put("myobj", myobj.identify());
   ...
   logger.error("this message contains info about myobj")
}

This is really helpful. Unfortunately there are tons of for looks like this where I forgot to use the mdc.put(). So I was thinking...would be some way to instrument the code so that:

  1. I detect there is a for looping over a collection of MyObjectType
  2. I insert this as first instruction inside the loop: MDC.put("myobj", myobj.identify());

If there is a way (using aop, instrumentation, some java agent?), how difficult would it be (maybe it's not worth the effort).

I have never used any java bytecode library, just spring aop lightly.

2
  • It is so a pity that Coccinelle doesn't support Java (yet)... Otherwise it'd have been the ideal tool for that job! Commented Dec 16, 2011 at 18:41
  • Instead of using magical tricks, try not to duplicate your code, because this is what caused you the problem. Commented Dec 16, 2011 at 20:54

3 Answers 3

1

If the iteration method is quite complex and you use it so much, maybe you should move it to a new utility class specifically for handling those functions? That way, you need to write something once and all the calls to the new static method will reuse the same code.

Sign up to request clarification or add additional context in comments.

Comments

0

You can change/add classes at runtime using javassist.
It's practically black magic.

I have also used janino with great success.

Comments

0

I believe you would have to do this at class loading time. I don't know how to do it myself. But our company uses an application by a vendor that instruments our application code this way.

It does seem odd to instrument something that should have been noticed by a programmer (IMHO). I was wondering why not use refactoring through an IDE like eclipse, etc., where you could locate all instances of something and then add the code? Both will require testing, but it will probably be tougher to debug issues to solve problems if you get your instrumentation wrong.

Just my opinion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.