Dynamic Compilation

Hi,
I am currently writing a system in which i need to dynamically generate a java source file, compile it, and then run it, all through Java.
To clarify, during the running of the program, a copy is taken of a current Java source file, and then additional method calls are inserted into the copy of the source file. Then i need to compile the "new" Java source file, and run the comiled class file.
is this possible? if so, how?
thanks
jamie.

It's not documented (or at least you can't download the documentation).
In my example, I'm importing from a subpackage v8. Open up your tools.jar and find out what the name of the packages are.
I've created a small app that gets the class info using reflection
package com.sun.tools.javac.v8;
import com.sun.tools.javac.v8.code.Symbol;
import com.sun.tools.javac.v8.tree.Tree;
import com.sun.tools.javac.v8.util.Context;
import com.sun.tools.javac.v8.util.List;
import java.io.InputStream;
public JavaCompiler implements ClassReader$SourceCompleter {
     public boolean verbose;
     public boolean sourceOutput;
     public boolean attrParseOnly;
     public boolean classOutput;
     public boolean printFlat;
     public boolean deprecation;
     public boolean warnunchecked;
     public boolean genCrt;
     public String encoding;
     public JavaCompiler(Context) {}
     public com.sun.tools.javac.v8.util.List compile(List) throws Throwable {}
     public void close() {}
     public Tree$TopLevel parse(String) {}
     public Tree$TopLevel parse(String, InputStream) {}
     public static String version() {}
     public void complete(Symbol$ClassSymbol, String, InputStream) throws Symbol$CompletionFailure {}
     public int errorCount() {}
     public static JavaCompiler make(Context) {}
     public InputStream openSource(String) {}
     public native int hashCode();
     public final native Class getClass();
     public final void wait() throws InterruptedException {}
     public final native void wait(long) throws InterruptedException;
     public final void wait(long, int) throws InterruptedException {}
     public boolean equals(java.lang.Object) {}
     public final native void notify();
     public final native void notifyAll();
     public java.lang.String toString() {}
}

Similar Messages

  • Dynamic compilation : getting number of errors

    Hi guys,
    in my application i'm dynamically compiling java files and then processing results later.
    In this i opted for the eclipse jdt compiler that i embedded in my application.
    At this stage i need to get a critical information from the compiler :
    if compilation fails i need a way to get how many errors were generated by the compiler ( Errors without warnings)
    Is it possible to get this information ?
    can we do that with eclipse jdt compiler API ? and how ?
    is there another way to solve this if we can't do it with jdt compiler ?
    I appreciate a lot any help on this issue.
    thanking you.

    Thanks, I got the answer. xfa.host.numPages provides me the n
    umber of pageas.

  • A Question for the Cracks - dynamic Compilation in Memory?

    HI
    i just wondered if it is possible to compile a java source file during runtime in MEMORY, means, without writing the class file to the filesystem but being able to create an instance of that compiled class file.
    I guess, theoreticaly this must be possible, since i could try to take the output of the compiler as an input stream in my application an save that stream as a String (or somehow different) and then try to create the an instance using classloader and serialization (somehow.... problem is, i don't know yet how this excatly could be done).
    I know, that question sounds a little bit strange, but I'm just thinking about a licening methode and this could do a very important part of it.
    So i would be very thankfull for any comment about this idea!
    josh

    Yeah, but here's the thing. If you provide the source files to the program, then you've put the thief one step closer to having your program (they don't have to decompile it.) Even if you encrypt the source, once they've decrypted that they're still one step closer than if you just encrypted the bytecode.
    In the encrypted class file solution, if the user doesn't have a legal license, they cannot run the program, because they cannot decrypt the classes. They have the encryption algorithm, but since they don't have a private key (which is in the license file) they can't load the code.
    The license also, would be one-license-per-user, with a multitude of different licenses able to decrypt the same encrypted classes. If you don't want a particular party to have the program, you just don't give them a key, or give them a key which decrypts only a certain set of classes (effectively providing them with a functional demo.)
    Even once the user has a license and your algorithm though, it still isn't trivial for them to make decrypted .class files out of them though, since your algorithm will load the classes as soon as they're created. They'd have to decompile and hack up the decryption code to write the classes back to files also.
    You could probably also figure out some way to stamp an ID on each decrypted class at runtime, so you can tell which user is running the program so if someone does distribute decrypted versions of the classes, you can tell which user did it and start legal proceedings. :-)

  • Dynamic compilation in memory

    Hello,
    I have used javax.tools.ToolProvider to compile a simple class that comes from a CharSequence object in memory, and it works just fine.
    Now, I need to reference another class that comes also from a CharSequence object in memory. Which method in the ForwardingJavaFileManager I should override to make this class available to the main class.
    Thank you
    The class I need to reference is in class (.class) format not the java source format (.java).
    Edited by: Gen.Java on Apr 23, 2013 2:05 AM

    CharSequence src = "public class DynaClass {public String toString (){return"hello";}}";Using javax.tools API, this compiles just fine. However,the following does not, complaining that it cannot find the class "another". The bytecode for the class "another" is in memory (not the file system). I just need to make it available to the main class "DynaClass".
    CharSequence src = "public class DynaClass {public String toString (){return new another().get();}}";The following is my code:
    import java.util.*;
    import javax.tools.*;
    import java.io.*;
    public class DynaCompTest
    public static void main(String[] args) throws Exception
    JavaCompiler         compiler;
    ClassFileManager     fileManager;
    List<JavaFileObject> jfiles;
    CharSequence         src;
    String               fullName;
    fullName = "DynaClass";
    src      = "public class DynaClass {public String toString (){return"hello";}}";
    compiler    = ToolProvider.getSystemJavaCompiler ();
    fileManager = new ClassFileManager ( compiler.getStandardFileManager(null, null, null) );
    jfiles      = new ArrayList<JavaFileObject>();
    jfiles.add  ( new CharSequenceJavaFileObject(fullName,src) );
    compiler.getTask ( null, fileManager, null, null, null, jfiles).call ();
    import java.net.*;
    import javax.tools.*;
    public class CharSequenceJavaFileObject extends SimpleJavaFileObject
    private CharSequence content;
    public       CharSequenceJavaFileObject (
    String       className,
    CharSequence content                    )
    super      ( URI.create("string:///" + className.replace('.', '/')+ Kind.SOURCE.extension), Kind.SOURCE);
    this.content = content;
    @Override
    public CharSequence getCharContent       (
    boolean             ignoreEncodingErrors )
    return content;
    import java.security.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.tools.*;
    import javax.tools.JavaFileObject.*;
    public class ClassFileManager extends ForwardingJavaFileManager<JavaFileManager>
    private final Map<String,JavaClassObject> fileObjects;
    public                  ClassFileManager (
    StandardJavaFileManager standardManager  )
    super       ( standardManager );
    fileObjects = new HashMap<String,JavaClassObject>();
    @Override
    public ClassLoader getClassLoader (
    Location           location       )
    return new ClassLoader() {
               @Override
               protected Class<?> findClass(String name) throws ClassNotFoundException {
                    JavaClassObject jco;
                    jco      = fileObjects.get(name);
                    byte[] b = jco.getByteCode();
                    return super.defineClass(name, b, 0, b.length);
    @Override
    public JavaFileObject getJavaFileForOutput (
    Location              location,
    String                className,
    Kind                  kind,
    FileObject            sibling              ) throws IOException
    JavaClassObject jco;
    jco             = new JavaClassObject(className, kind);
    fileObjects.put ( className,jco );
    return jco;
    import java.net.*;
    import java.io.*;
    import javax.tools.*;
    public class JavaClassObject extends SimpleJavaFileObject
    protected final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    public JavaClassObject (
    String className,
    Kind   kind            )
    super ( URI.create("string:///" + className.replace('.', '/')+ kind.extension), kind );
    public byte[] getByteCode ()
    return bos.toByteArray();
    @Override
    public OutputStream openOutputStream () throws IOException
    return bos;
    }

  • How to compile a java file Dynamically !!!!

    Hi all
    The problem is
    I have a dynamically created java file ,and i want to compile that file dynamically itself. The file name is stored in a string,
    I am using ECLIPSE editor..
    How do i compile this java file (which is stored in a string) dynamically?
    Pls help me, already wasted a lot of time,
    Thanks in advance

    In every Tutorial regarding Dynamic Compilation,
    It is told to import javax.tools.*..
    But i cannot find this package
    I am using jdk1.4, is this the reason?
    Actually the following packages are needed fro this
    import javax.tools.DiagnosticCollector;
    import javax.tools.JavaCompiler;
    import javax.tools.JavaFileObject;
    import javax.tools.StandardJavaFileManager;
    import javax.tools.ToolProvider;
    but i cant finad any..!!!
    Please help me

  • Is there such thing as a "compile and execute statement" in Java?

    I wanted to know if there's any way to compile and execute a program "within" another program.

    Yes, but the classes to do so aren't officially supported by Sun as far as I know.
    And you must be able to assume a thing or two about the stuff you compile, such as existing constructors or factory methods etc, otherwise it gets hairy.
    Here's some example code (haven't tried it, so excuse any spelling errors etc) to compile the source code in a file called MyClass.java:
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new sun.tools.javac.Main(baos,null).compile("MyClass.java");
    String theMsg = baos.toString();
    if (theMsg.length() > 0)
        // NiftyErrorHandlingHere
    }After that, you can load it with a simple ClassLoader.loadClass() call and create instances of it.
    It must be compiled with the tools.jar file in the classpath, to find the sun.tools.javac.Main class.
    However, for any such dynamically compiled class to be of any use to you, you must be able to assume something about it, such as implementing interfaces or whatever, otherwise it's a kind of pointless exercise.
    HTH,
    F

  • Include an in-memory jar file for JSR-199 compilation

    I want to compile a source file in memory, which requires a jar file that is also represented in memory. I used the JavaSourceFromString class recommended in the documentation for the class JavaCompiler and in a demo I found online that shows how to compile sources represented as String in memory. To represent the jar file, I used a similar trick to JavaSourceFromString:
    public class JarJavaFileObjectFromByteArray extends SimpleJavaFileObject {
       * The contents of this jar file.
      private final byte[] contents;
       * Constructs a new JarJavaFileObjectFromByteArray given the name and binary
       * contents of a jar file.
       * @param name the name of this jar file
       * @param contents the contents of this jar file
      public JarJavaFileObjectFromByteArray(String name, byte[] contents) {
        super(newURI(name), Kind.OTHER);
        this.contents = contents;
      ... // code not shown ensures that the URI returned from newURI is of the form,
          // for instance, bytes:///MathConstants.jar, if the name of the jar file is MathConstants.jar
      @Override
      public InputStream openInputStream() throws IOException {
        return new ByteArrayInputStream(contents);
    }However, I do not know how to alert the compiler that this jar file should be on the classpath. I tried this:
    List<String> options = Arrays.asList(" -classpath bytes:///MathConstants.jar ");
    CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits);but I get the following error when calling getTask:
    java.lang.IllegalArgumentException: invalid flag: -classpath bytes:///MathConstants.jarI assume there is some way to tell the compiler, "look at the MathConstants.jar file that I am storing in memory when searching the classpath", but I do not know how to do this. I assumed that the options parameter for getTask represents command-line flags that would be passed to the compiler if this were happening on the command line (such as "-cp .", which also does not work), but perhaps this assumption is wrong.

    Hi Bruce,
    I have a question regarding loading a jar file by the compiler to dynamically compile with a source file. I hope you can probably offer me an idea on what has been missing or wrong with the source codes I have written for my application.
    I am using Eclipse compiler to dynamically compile a class. In the class, I want it to make a reference to a jar file for compilation dynamically.
    Here is the source of a test class I wrote:
    import javax.servlet.http.HttpServlet;
    class MyServlet extends HttpServlet {
    }The import statement refers to the class javax.servlet.http.HttpServlet from the jar file C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\lib\\servlet-api.jar placed in the file system.
    In the method called compileClass (shown below), I used the path of the jar file to add to the option -classpath as you suggested.
         private static CompileClassResult compileClass(Writer out, String className, String classSource) {
              try {
                   JavaCompiler javac = new EclipseCompiler();
                   StandardJavaFileManager sjfm = javac.getStandardFileManager(null, null, null);
                   SpecialClassLoader scl = new SpecialClassLoader();
                   SpecialJavaFileManager fileManager = new SpecialJavaFileManager(sjfm, scl);
                   List<String> options = new ArrayList<String>();
                   options.addAll(Arrays.asList("-classpath", "C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\lib\\servlet-api.jar"));
                   List<MemorySource> compilationUnits = Arrays.asList(new MemorySource(className, classSource));
                   DiagnosticListener<JavaFileObject> diagnosticListener = null;
                   Iterable<String> classes = null;
                   if (out == null) {
                        out = new PrintWriter(System.err);
                   JavaCompiler.CompilationTask compile = javac.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits);
                   boolean res = compile.call();
                   if (res) {
                        //Need to modify the api to return an array of two elements - one classes and other bytecodes for all classes in the same class file.
                        return CompileClassResult.newInstance(scl.findClasses(), scl.findByteCodes());
              } catch (Exception e) {
                   e.printStackTrace();               
              return null;
         }I also extended the class ForwardingJavaFileManager as you suggested and have it delegated to the StandardJavaFileManager sent to the compiler mentioned in the method compileClass above. The extended class (called SpecialJavaFileManager) is as follows:
    public class SpecialJavaFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> {
         private SpecialClassLoader xcl;
         public SpecialJavaFileManager(StandardJavaFileManager sjfm, SpecialClassLoader xcl) {
              super(sjfm);
              System.out.println("SpecialJavaFileManager");
              this.xcl = xcl;
         public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
              System.out.println("getJavaFileForOutput");
              MemoryByteCode mbc = new MemoryByteCode(name);
              xcl.addClass(name, mbc);
              return mbc;
         public Iterable<JavaFileObject> list(JavaFileManager.Location loc, String pkg, Set kinds, boolean recurse) throws IOException {
              System.out.println("list ");
            List<JavaFileObject> result = new ArrayList<JavaFileObject>();
            for (JavaFileObject f : super.list(loc, pkg, kinds, recurse)) {
                 System.out.println(f);
                result.add(f);
              return result;
    }I run the application and the result shows that it didn't load the jar file into the memory as expected. From the output (below) I got, it doesn't seem to invoke the method list(...) in the class SpecialJavaFileManager.
    SpecialJavaFileManager
    1. ERROR in \MyServlet.java (at line 1)
         import javax.servlet.http.*;
                ^^^^^^^^^^^^^
    The import javax.servlet cannot be resolved
    2. ERROR in \MyServlet.java (at line 3)
         class MyServlet extends HttpServlet {
                                 ^^^^^^^^^^^
    HttpServlet cannot be resolved to a typeWould you please let me know what has possibly be missing or wrong?
    Thanks.
    Jonathan
    Edited by: jonathanlam on Aug 10, 2009 6:47 PM

  • Add jar for in-memory compilation by Eclipse Compiler

    Hi,
    I have a question regarding loading a jar file by the compiler to dynamically compile with a source file. I hope someone can probably offer me an idea on what has been missing or wrong with the source codes I have written for my application.
    I am using Eclipse compiler to dynamically compile a class. In the class, I want it to make a reference to a jar file for compilation dynamically.
    Here is the source of a test class I wrote:
    import javax.servlet.http.HttpServlet;
    class MyServlet extends HttpServlet {
    }The import statement refers to the class javax.servlet.http.HttpServlet from the jar file C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\lib\\servlet-api.jar placed in the local file system.
    In the method called compileClass (shown below), I used the path of the jar file to add to the option -classpath as suggested in another thread (http://forums.sun.com/thread.jspa?threadID=5306520&start=0&tstart=0).
    private static CompileClassResult compileClass(Writer out, String className, String classSource) {
              try {
                   JavaCompiler javac = new EclipseCompiler();
                   StandardJavaFileManager sjfm = javac.getStandardFileManager(null, null, null);
                   SpecialClassLoader scl = new SpecialClassLoader();
                   SpecialJavaFileManager fileManager = new SpecialJavaFileManager(sjfm, scl);
                   List<String> options = new ArrayList<String>();
                   options.addAll(Arrays.asList("-classpath", "C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\lib\\servlet-api.jar"));
                   List<MemorySource> compilationUnits = Arrays.asList(new MemorySource(className, classSource));
                   DiagnosticListener<JavaFileObject> diagnosticListener = null;
                   Iterable<String> classes = null;
                   if (out == null) {
                        out = new PrintWriter(System.err);
                   JavaCompiler.CompilationTask compile = javac.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits);
                   boolean res = compile.call();
                   if (res) {
                        //Need to modify the api to return an array of two elements - one classes and other bytecodes for all classes in the same class file.
                        return CompileClassResult.newInstance(scl.findClasses(), scl.findByteCodes());
              } catch (Exception e) {
                   e.printStackTrace();               
              return null;
         }I also extended the class ForwardingJavaFileManager as suggested in the thread mentioned above and have it delegated to the StandardJavaFileManager sent to the compiler mentioned in the method compileClass above. The extended class (called SpecialJavaFileManager) is as follows:
    public class SpecialJavaFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> {
         private SpecialClassLoader xcl;
         public SpecialJavaFileManager(StandardJavaFileManager sjfm, SpecialClassLoader xcl) {
              super(sjfm);
              System.out.println("SpecialJavaFileManager");
              this.xcl = xcl;
         public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
              System.out.println("getJavaFileForOutput");
              MemoryByteCode mbc = new MemoryByteCode(name);
              xcl.addClass(name, mbc);
              return mbc;
         public Iterable<JavaFileObject> list(JavaFileManager.Location loc, String pkg, Set kinds, boolean recurse) throws IOException {
              System.out.println("list ");
            List<JavaFileObject> result = new ArrayList<JavaFileObject>();
            for (JavaFileObject f : super.list(loc, pkg, kinds, recurse)) {
                 System.out.println(f);
                result.add(f);
              return result;
    }I run the application and the result shows that it didn't load the jar file into the memory as expected. From the output (below) I got, it doesn't seem to invoke the method list(...) in the class SpecialJavaFileManager.
    SpecialJavaFileManager
    1. ERROR in \MyServlet.java (at line 1)
         import javax.servlet.http.*;
                ^^^^^^^^^^^^^
    The import javax.servlet cannot be resolved
    2. ERROR in \MyServlet.java (at line 3)
         class MyServlet extends HttpServlet {
                                 ^^^^^^^^^^^
    HttpServlet cannot be resolved to a typeDoes somebody know what I probably have missed or done wrong in the codes?
    Thanks.
    Jonathan

    Hi jschell,
    I read the thread referred to by the link you gave and tried to add the path using the setLocation method:
    JavaCompiler javac = new EclipseCompiler();
    StandardJavaFileManager sjfm = javac.getStandardFileManager(null, null, null);
    SpecialClassLoader scl = new SpecialClassLoader();
    List<File> path = Arrays.asList(new File("C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\lib\\servlet-api.jar"));
    sjfm.setLocation(StandardLocation.CLASS_PATH, path);
    SpecialJavaFileManager fileManager = new SpecialJavaFileManager(sjfm, scl);After I run the file with the change, I still didn't get the compiler to read the jar the file.
    Anyone knows how to solve this issue?
    Thank you.
    Jonathan

  • How can I allow user to customize the functionality of program at runtime? (not using runtime code compilation)

    Using .NET Framework 4.0 what features are available that would allow to accomplish something very modular and user customizable, like depicted in this XML.  Where I define specific base operations like Get() and Put() methods that operate on strings. 
    And allow the user to add and remove those or mix and match them in a way that they basically design their own run time functionality that suits them.  So they just create their own 'Operation' and fill it with the operations they want to perform on some
    incoming data type, in this case it is a string - with substring and insert methods. 
    EDIT - Assuming end user is non programmer and Dynamic Code compilation is not an option.  I have an idea maybe using dynamic keyword, but not sure if it makes what i suggest possible.
    <Operation Name="GetValues">
      <Get id=123"  FromIndex="2" ToIndex="23"/>
      <Get id="234"  FromIndex="3" ToIndex="5"/>
       <Output Path="C:\" Filename="testOut.txt" Append="true">
         <Format>
              <Result id="123"/> , <Result id="234"/>
         </Format>
       </Output>
    </Operation>
    <Operation Name="InsertValue">
      <Put AtIndex="5">stringtoinsert</Put>
      <Put AtIndex="36">anotherstringtoinsert</Put>
    </Operation>

    Hi sjs1978,
    I am not familiar with dynamic code, and I made a research about it.
    >> I'm aware of dynamic code compilation, but that requires user to input pieces of code.
    Did you try to store the pieces of code into a file and call the code when the dynamic code compilation requires user to input code?
    In addition, I found links about using code provider to compile a source file, and the links below might be useful to you.
    # Dynamic Source Code Generation and Compilation
    https://msdn.microsoft.com/en-us/library/650ax5cx(v=vs.110).aspx
    # CSharpCodeProvider Class
    https://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider(v=vs.110).aspx
    # Is it possible to dynamically compile and execute C# code fragments?
    http://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-sharp-code-fragments
    Best Regards,
    Tony
    Help each other

  • Compiling one java file within another java program

    Hi all,
    I want to compile one java file say one.java within a java program say second.java.. i simply have no idea as how to proceed ..pls help!!

    http://onesearch.sun.com/search/onesearch/index.jsp?qt=dynamically+compile&subCat=siteforumid%3Ajava31&site=dev&dftab=siteforumid%3Ajava31&chooseCat=javaall&col=developer-forums
    Just to give you an idea.

  • Compile code in a file

    i have some java codes in my "fl.txt"(c:\fl.txt). these are;
    public class file_{
    public static void main(String args[]){
    System.out.print("hello world");
    }i want to compile these code from my program(i am building it with java) at runtime.. how can ii do that.i think i need to use runtime.exec() method but i dont know how can i compile these codes in a file....

    It is possible to dynamically compile code from within a running Java program,
    but you should have a damn good reason for doing so.
    Check out the documentation for javac: http://java.sun.com/javase/6/docs/technotes/tools/windows/javac.html
    <quote>
    javac supports the new Java Compiler API defined by the classes and interfaces in the javax.tools package.
    Example
    To perform a compilation using arguments as you would give on the command line, you can use the following:
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    int rc = javac.run(null, null, null, args);This will write any diagnostics to the standard output stream, and return the exit code that javac would give when invoked from the command line.
    You can use other methods on the javax.tools.JavaCompiler interface to handle diagnostics, control where files are read from and written to, and so on.
    </quote>
    If you are using an older version of Java, check out the documentation to see the old interface to do this (com.sun.tools.javac.Main).

  • Dynamic code downloading

    Could java interpreter execute ANY classes /or maybe automatically download it first/ remotely from network via HTTP, and not only from local disk? If yes, how this could be done?

    You could certainly download code dynamically, compile and run it with java. There's no problem there.

  • Compiling .java files during program execution.

    I have a program that read events in from a file and creates custom Event objects (which extend Thread) from this information, and then later the events are activated depending on the timing information that was provided in the file. Everything works great however, I would like to add the ability to include custom Events in the file that the events are read from. I would like the program to take that java code information and produce a class file that can be used during the programs execution. What classes can help me do this and are there any examples that anybody knows of, of something like this?

    I wonder if anyone has ever tried to do this before...
    http://onesearch.sun.com/search/developers/index.jsp?col=devforums&qp_name=Java+Programming&qp=forum%3A31&qt=dynamic+compilation+compile+runtime

  • Running Dynamic Code - Is it possible?

    Hi guys,
    I am interested to know whether there is a way I can run dynamic code in my java program. For example, I want to be able to write java code into a JTextArea and then run that code as like an extension of the program.
    In other words, if I wrote something simple like "System.out.println("Hi");, it would print the work "Hi" in the console as if it were part of the original program.
    Does anyone know if there is a way to do this? Alternatively, is there a way I can call the Javac tool from within a program, thus allowing me to dynamically compile a program.
    Thanks guys,
    WATTO
    [email protected]
    http://www.watto.org

    I think JSP is a variant of such a frame. You can
    execute a code compiling it.JSP is normally compiled into bytecode when it is first loaded by the container.
    beanshell and [url http://www-124.ibm.com/developerworks/projects/bsf]BSF are, I think what the poster is after, on this very frequently asked question :)

  • Eclipse jdt compiler/tomcat

    Hi all,
    this question is for those familiar with the eclipse jdt compiler.
    Im my web application i'm trying to dynamically compile a java file that i'm saving in a dir under my webapps folder say "mydir"
    for the comipaltion i'm using the eclipse jdt compiler but to get it work i need to specify the classpath argument for the Main.compile() method to work.
    now what is the default classpath of tomcat server ?
    or saying it in other way what should be the classpath i should use as arguments in Main.compile() method of jdt ?
    thanking you.

    well let me explain this more :
    i'm using the following code for dynamic compilation :
    ByteArrayOutputStream baosMessages = new ByteArrayOutputStream();
              ByteArrayOutputStream baosWarnings = new ByteArrayOutputStream();
    StringBuffer warnings = new StringBuffer();
    String classpath ="";
    //           Start compilation using jdtcore
              boolean compilationStatus = org.eclipse.jdt.internal.compiler.batch.Main
                    .compile("-1.5 -source 1.5 -warn:" + warningSetting + " "
                 + classpath + file ,
                 new PrintWriter(baosMessages), new PrintWriter(
              baosWarnings));
    StringBuffer compilerMessages=new StringBuffer();
              long time1 = System.currentTimeMillis();
              public  void compile() throws Exception {
              BufferedReader br = new BufferedReader(new InputStreamReader(
                    new ByteArrayInputStream(baosMessages.toByteArray())));
              while (true) {
                 String str = br.readLine();
                 if (str == null) {
                    break;
                // this._logger.info("/javac/ " + str);
                 compilerMessages.append(str+"\n");
              BufferedReader brWarnings = new BufferedReader(
                    new InputStreamReader(new ByteArrayInputStream(baosWarnings
                 .toByteArray())));
              while (true) {
                 String str = brWarnings.readLine();
                 if (str == null) {
                    break;
                 //this._logger.warning("/javac/ " + str);
                 compilerMessages.append(str+"\n");
                 warnings.append(str+"\n");
              System.out.println(compilerMessages.toString()+"\n\n"+warnings.toString());
              System.out.println((time1 - time0) + " milliseconds, "
                    + (compilationStatus ? "success" : "failure"));
         }Now when i run the servlet containing above code the result of compilation tells me :
    No such directory : null
    i'm suspecting i'm missing the class path . is that true ?
    can u help ?

Maybe you are looking for

  • ITunes comes up with an error message

    When I go to start iTunes a popup comes up, it says ' iTunes has encountered a problem and needs to close'. It gives the option to send an error report to Windows. What can i do? Someone please help. I've tried reinstalling iTunes and turning off nor

  • Error with listener in Oracle 11.2

    I start listener successfully but could not connect to instance by listener :(, I can't understand why this happen, please help, this is urgent [oracle@TEST01 admin]$ lsnrctl start TEST LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 12-APR-201

  • BT support tell me one thing & BT sales the opposi...

    Hi I have had vision since Sept 09 with a espn card which has always and still works ok I ordered sky sport 1 & 2 and the channels are 41 & 42 with 71% strength & 100% quality. But the box asks for a viewing card for theses channels but not for 34 es

  • Photoshop CS5 - only the tools show?

    I have installed Photoshop CS5 and when I open the programme only the tools show - there is a gap in the middle where I can see my screen saver or another programme through?  I also can't open via Lightroom (even though Photoshop is an option for edi

  • Viewing Timelapse movies/videos

    Hi, I am new to this timelapse movies/videos. I have tried capturing a video and wanted to watch the results, however the frame moves pretty fast. Pausing the video and pressing a bit longer on the frame location reveals more sequence of frames. How