I'm wondering if anybody knows a way to dynamically create a Java class, or more specifically a method in a Java class. I'm trying to do some unit testing, so I have code that I've already written, and I'm always modifying the code by adding extra System.out.println statements and then deleting them when I'm finished (otherwise the开发者_运维百科 code gets too cluttered). What I'm trying to do is write a framework that can take a method, copy its code, add the System.out.println statements automatically, and then run the test on the copied method. This might also save time recompiling an entire Java application when I've only made a minor change to get some extra info while debugging.
Any ideas would be greatly appreciated.
You could just use a logging framework.
Sounds like you need aspects, i.e. AspectJ.
One option is to use cglib (Code Generation Library).
I don't have a specific example, but Aspect Oriented Programming (AOP) is what you want. Take a look at AspectJ.
精彩评论