views:

71

answers:

1

Hello all.

In a project I'm currently working on, I need to generate Java classes at runtime. I also need to avoid using reflection when using these classes later on.

I've been search for current solutions to do this, and found Javassist and Java 6 Java Compiler API.

I'm confused though:

  1. What does Javassist uses to generate classes? Does it uses reflection or something?

  2. I've coded some tests and found it pretty easy to generate bytecode from source code, and then load classes from the generated bytecode. What are the advantages of using Javassist over this solution?

+1  A: 

Javassist has several options, one being a small included compiler allowing you to convert Java snippets to byte code, making it easy to insert e.g. a "System.out.println(....)" or "log.debug(...)" statement in existing classes.

I wrote an article on this a while back, which shows how it can be done. See http://blogs.sun.com/CoreJavaTechTips/entry/add_logging_at_class_load. Note: For a production setting this approach should not be used - then you should consider using Aspect Oriented Programming in your application.

Thorbjørn Ravn Andersen
In this case, I won't need to do class transformation. Do you still think Javassist is still better? Or that it really doesn't matter which I go for?
halfwarp
Depends on what exactly you need to do. Feel free to add a use case to your question.
Thorbjørn Ravn Andersen
It's just a simple arithmetic expression evaluation method, to avoid using reflection or something like a visitor pattern...
halfwarp
How frequently will you create this?
Thorbjørn Ravn Andersen
Just once. Compile the generated class, get a single instance of it, and then just make the use of this object.
halfwarp