Skip to main content

Dynamically modifying Java class structure

3 replies [Last post]
Joined: 2006-11-19


I am trying to develop a solution to automatically insert new constructors to existing classes. I've considered using AspectJ to do it, however as far as I know it will only work if the name of the class to be modified was known beforehand (has to be hardcoded in the aspect), which is not applicable in my case.

So, can anyone give me some suggestions or recommendations on this? Especially in terms of:
- Is Aspectj the best tool to do this? If so, how to do it without hardcoding class names?
- Should I look at bytecode engineering/manipulation tools instead? If so, what's the most suitable library for my case (since I am aware that there are a lot of choices out there when it comes to bytecode manipulation)?

Thanks a lot for any helps, suggestions, and ideas.



Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2006-06-18

Do you have tougth to try groovy language for that. See


Joined: 2004-06-19

Hi, there are two ways I can think to approach this. Firstly the byte-code engineering way would be a good one to try. Look at the BCEL library for working with instrumenting byte codes (you can also work at a higher level, you don't need to code everything at the Java bytecode level) which can transform a class.

The other (easier) approach if you access to the source is to use the new Compiler API in java 1.6. This will be easier since you can operate on the source file of the class you want to modify as a piece of text and then dynamically recompile and reload that class.

Google for tutorials on the Java Compiler API (JSR-199) for example code and things. Note I'm not talking about the semi-supported javac.Main compiler hack that was used pre1.6, this is now a fully supported public API in 1.6.

Joined: 2008-03-24

Agree, and you can use Java assist instead of BCEL, that is more easy to use.