Dynamic class creation in Java - java

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.

Related

How to add Java annotation over methods during runtime [duplicate]

Is there a way to modify .class files in order to add Java annotations to certain methods? Basically I want to traverse methods of each class file in a jar file and annotate certain ones. Note that this is not at run-time while using the jar file. Rather, after I'm done I want to have modified class files with the annotations.
I do have access to the source code, so if there's an automatic source code modifier, that would work as well...
I'm assuming I'll need a tool such as Javassist or ASM. If so, which one should I use and how would I go about it?
Actually, this is a classic use case for AspectJ:
declare #method : public * BankAccount+.*(..) : #Secured(role="supervisor")
While I will grant you that direct byte code manipulation is more powerful, AspectJ is much more user-friendly, and it immediately gives you compiler warnings when you are doing something wrong.
Also, if you use Load Time Weaving, you can leave the original library jar unchanged, because the weaving happens at class-load time.
Reference:
Declare Annotation
AspectJ in Action (book)
Googling for an hour or so turned this article up which seems to completely answer my question: use ASM. To write class files using the changed bytecode, use ClassWriter.
Well, time to get to work then, I guess. :)

change the content of debug view in eclipse

I'm writing a java framework, for a class file, sample.class, it generates a proxy file sample_proxy.class. When sample.testMethod() is called, it excutes sample_proxy.class. I already make an eclipse plugin to make the breakpoint work,
If I start from Main.java, and make a breakpoint in sample.testMethod(), the stack below looks like: Main.main-->sample.proxy_method-->sample_proxy.testMethod.
Is there any way to ingore the proxy to show like: Main.main-->sample.testMethod?
What you want to do is possible but a bit more complicated. First of all there is no way to change the StackTrace of a running program. So Thread.currentThread().getStackTrace() is not the way to go.
I'm writing a java framework, for a class file, sample.class, it
generates a proxy file sample_proxy.class.
When you do that, you have to inline the called method, instead of simply calling it. That is non-trivial technique also being used by ProGuard. You will find that it does different kinds of inlining. Most interested you could be in the functionality of "inlining short methods".
I suggest you copy it from the code there. I good point to start would be http://sourceforge.net/p/proguard/code/ci/default/tree/src/proguard/optimize/Optimizer.java#l156
But be aware that this requires fundamental knowledge about the JVM itself, so there won't be a simple code snippet that does what you want, in the context you expect.
I hope it helps.

Java: Print every method called to console?

I need to understand a quite large Java project. I browse through it with eclipse and use the call hierarchy and all, but that doesnt get me quite the idea on what is happening when the project runs (it's a webservice).
Is there a possibility to print out every method call with parameters to console?
Basically something that puts
System.out.println("methodName, params: " + param1.toString());
in every method for me.
Some kind of framework that provides that for example?
You should try to use Aspect-oriented programming (AOP).
Here is an example that does more or less what you want: How to use AOP with AspectJ for logging?

How to edit Java Platform Package (Built-in API) source code?

As good as the Java API is, I need to change the code of some classes in the default API packages (for example java.util.Scanner) for a project I am working on.
Ideally, I would extend the classes I am interested and create my own sub-classes, but the classes I want to extend are declared 'final'. How do you suggest I do this? Will I get into trouble with the compiler if I customize the source code of these packages?
If you can, you should rather wrap and delegate, as suggested in another answer. See the Adapter Pattern.
But there are of course ways to do this if you really need it.
A straightforward approach is to simply modify the code in downloaded sources and substitute your own version of a jar in the classpath.
Another option is to use aspect-oriented programming techniques, likely with AspectJ to intercept and modify calls as needed.
It might also be possible to hack together a solution using reflection and home-grown classloaders, but it will be painful to code.
All of these are however quite risky if you don't know what you're doing. Frequently classes are made final for good reason.
If you tell us more specifically what it is you're hoping to change, we might be able to provide assistance in avoiding what you currently think you need.
you really cant extend a final class..
if u really want to add a functionality by extending a class you can do it by modifying class src. from JDK and save it as your own class and use it.
Don't do that. Write your own code which wraps around the original scanner and use that. To update internal packages, there is an endorsed directory property which you can provide at runtime.
Never do it! Never change core classes. If class is final - use composition not inheritance.

How do I catch the read and writes in a java program?

I am trying to create a tool that can capture all the read and writes made by a java program. Also, I would like to know what fields of what object is access/modified.
I currently looked at:-
1) java.lang.instrument
I could not do much with that. I could not understand how to write an agent that can get access to the a running program and create a watch on different objects/fields and anything related. I would appreciated if you have any idea or information on that.
2) jvmti
I looked at jvmti and tried to create a jvmti tool, but I figured out that to get the objects, I would need the JVMTI_EVENT_OBJECT_ALLOC be a potential capability. But, I figured that, it is not. Moreover, I read that this event is not called for new command. Hence, at the moment, even this does not seem applicable.
So, I would like to know if you guys know any way to do what I want to do, either using the above mentioned methods or any other technique/tool that you may be aware of?
NOTE: I do not have access to the source code of the application. All, I have are the class files.
Check these out:
http://download.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html
http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html
http://jamonapi.sourceforge.net/
http://www.manageengine.com/products/applications_manager/java-runtime-monitoring.html
It's very easy to do with the ASM lib. Create a new Class Loader that instruments all classes before loading them and use it for loading the target classes. Create a new MethodAdapter and override the visitFieldInsn method. Then look for the PUTFIELD, PUTSTATIC, GETFIELD and GETSTATIC opcodes. Although this might look scary (as my explation is most likely gibberish), it's in fact pretty easy. Just download the ASM manual and you'll know how to do it in no time.
Edit: I was forgetting to tell that in order to be able to intercept the reads and writes of done by the JDK code you have to instrument those classes, save them to files and run the JVM with a modified bootstrap classpath, through command line argument -Xbootclasspath (java.* and some other packages; I believe that at least sun.* and javax.* also need this).
This may also be doable with AspectJ... but I'm not sure.

Categories