Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generating / Compiling class at runtime  RSS feed

 
Ranch Hand
Posts: 3640
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a String that contains definition of class. I want to compile it and execute method of it, without storing that String in a physical class file.

How to achieve this?
 
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've found the Javassist library very useful for creating classes in-memory, but I'm not sure if it accepts a complete class as input. You may have to break it down to methods.
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://mindprod.com/jgloss/onthefly.html

Runtime compilation can be done as above. You could use a combination of MemorymappedIO, Reflection, Classloader to achieve execution.

Mustang has support for Compiler API.

Jeevan
[ November 17, 2006: Message edited by: Jeevan Philip ]
 
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You guys are blowing my mind. I had no idea this was possible.

-Cameron McKenzie
 
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JSP's are translated to servlets and then compiled to class files before it becomes usable.

And I do not think that tomcat(or any other compiler uses.) uses javac.exe for that..
There are classes available in tools.jar for compiliig java files at runtime.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And I do not think that tomcat(or any other compiler uses.) uses javac.exe for that..
There are classes available in tools.jar for compiliig java files at runtime.

Older versions of Tomcat used javac for this; these days it ships with the Eclipse Compiler (JDT). It did't use javac.exe, because that's just a command-line wrapper around the javac classes, but instead used the compiler classes directly (chiefly com.sun.tools.javac.Main).

But neither JDT nor javac work in-memory - both write .java and .class files to disk. You can find those in the work directory of your Tomcat installation.
 
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you can use it, Java 6 has a bunch of new APIs to access the compiler. See javax.tools package.
 
Chetan Parekh
Ranch Hand
Posts: 3640
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everybody for your kind reply!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!