Java6: How to compile java using JavaCompiler class

Hi all,
Using JavaCompiler, we can run the java program thru programmaticaly using run() method.
Could anyone please tell me how to compile a java program using JavaCompailer class? Or calling run() itself will compile java file?
Thanks
Shagil

import spoon.support.input.SpoonInputStream;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.comp.Attr;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.comp.Todo;
import com.sun.tools.javac.tree.Tree;
import com.sun.tools.javac.tree.Tree.ClassDef;
import com.sun.tools.javac.tree.Tree.TopLevel;
import com.sun.tools.javac.util.Abort;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Name;
* The Spoon compiler (uses javac).
public class SpoonCompiler extends com.sun.tools.javac.main.JavaCompiler {
     Attr attr;
     Enter enter;
     boolean hasBeenUsed = false;
     Log log;
     Todo todo;
     public SpoonCompiler(Context arg0) {
          super(arg0);
          enter = Enter.instance(arg0);
          todo = Todo.instance(arg0);
          log = Log.instance(arg0);
          attr = Attr.instance(arg0);
          sourceOutput=true;
      * Main method: compile a list of files, return all compiled classes
      * @param filenames
      *            The names of all files to be compiled.
     @SuppressWarnings("unused")
     public List<Tree> parseAndAttribute(List<SpoonInputStream> filenames)
               throws Throwable {
          // as a JavaCompiler can only be used once, throw an exception if
          // it has been used before.
          assert !hasBeenUsed : "attempt to reuse JavaCompiler";
          hasBeenUsed = true;
          long msec = System.currentTimeMillis();
          ListBuffer<ClassSymbol> classes = new ListBuffer<ClassSymbol>();
          try {
               // parse all files
               ListBuffer<Tree> trees = new ListBuffer<Tree>();
               for (List<SpoonInputStream> l = filenames; l.nonEmpty(); l = l.tail) {
                    trees.append(parse(l.head.getFileName(),l.head.getStream()));
               // enter symbols for all files
               List<Tree> roots = trees.toList();
               if (errorCount() == 0)
                    enter.main(roots);
               // If generating source, remember the classes declared in
               // the original compilation units listed on the command line.
               List<ClassDef> rootClasses = null;
               if (sourceOutput || stubOutput) {
                    ListBuffer<ClassDef> cdefs = new ListBuffer<ClassDef>();
                    for (List<Tree> l = roots; l.nonEmpty(); l = l.tail) {
                         for (List<Tree> defs = ((TopLevel) l.head).defs; defs
                                   .nonEmpty(); defs = defs.tail) {
                              if (defs.head instanceof ClassDef)
                                   cdefs.append((ClassDef) defs.head);
                    rootClasses = cdefs.toList();
               while (todo.nonEmpty()) {
                    Env<AttrContext> env = todo.next();
                    // save tree prior to rewriting
                    Tree untranslated = env.tree;
                    // attribution phase
                    if (verbose)
                         printVerbose("checking.attribution", env.enclClass.sym);
                    Name prev = log.useSource(env.enclClass.sym.sourcefile);
                    attr.attribClass(env.tree.pos, env.enclClass.sym);
               return trees.toList();
          } catch (Abort ex) {
               ex.printStackTrace();
          if (verbose)
               printVerbose("total", Long.toString(System.currentTimeMillis()
                         - msec));
          int errCount = errorCount();
          if (errCount == 1)
               printerCount("error", errCount);
          else
               printerCount("error.plural", errCount);
          if (log.nwarnings == 1)
               printerCount("warn", log.nwarnings);
          else
               printerCount("warn.plural", log.nwarnings);
          return null;
     private void printerCount(String str, int val) {
          System.err.println(str + " - " + val);
     private void printVerbose(String arg0, Object obj) {
          System.out.println(arg0 + " - " + obj.toString());
--- NEW FILE: CtBuilder.java ---
package spoon.support.builder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;
import spoon.query.Query;
import spoon.query.TypeFilter;
import spoon.reflect.CtFactory;
import spoon.reflect.code.BinaryOperatorKind;
import spoon.reflect.code.CtAbstractInvocation;
import spoon.reflect.code.CtArrayAccess;
import spoon.reflect.code.CtAssert;
import spoon.reflect.code.CtAssignment;
import spoon.reflect.code.CtBinaryOperator;
[...1760 lines suppressed...]
            var.setSimpleName(tree.sym.name.toString());
            var.setModifiers(getModifiers(tree.mods.flags));
            enter(var, tree);
            scan(tree.init);
            exit(var, tree);
    @Override
    public void visitWhileLoop(WhileLoop tree) {
        CtWhile whileLoop = new CtWhileImpl();
        enter(whileLoop, tree);
        builderContext.loopParameter = 1;
        scan(tree.cond);
        builderContext.loopParameter = 0;
        scan(tree.body);
        exit(whileLoop, tree);
}

Similar Messages

  • How to compile java to exe by JDeveloper?

    How to compile java to exe by JDeveloper?

    You used to be able to use exegen to generate stand alone executables for Windows, but this no longer works in later versions of Windows. It works for Windows 98 and NT. For example
    exegen/main:schedserv /out:sched.exe schedserv.class scheduler.class
    will generate the executable sched.exe from the two class files.
    Probably MicroSoft decided to make life a bit harder for Java users.

  • How is the java.lang.StringBuffer class different from the java.lang.String

    How is the java.lang.StringBuffer class different from the java.lang.String class?....

    Read the API.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
    "Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings."
    Although when possible you should use StringBuilder instead of StringBuffer.
    Always read the API at the very least before asking questions in the forums. Ideally you should do some google searching and poke around for an answer too. Otherwise you will get people barking at you.
    Drake

  • How to run java using xcode?

    i have to install "java developer " but i can't find, where i can run Java, Please give me information about "how to run java use xcode " ?

    Download the SDK from Oracle, code, enjoy.

  • How to compile Java files using Ant in Eclipse

    Hi All ,
    I would like to compile all Java files using Ant in Eclipse.Since am very new to Ant and Eclipse can someone help me to create a build.xml file and let me know how to compile all the java files.
    For ex , I have placed my java files inside the path C:\HEC\Terab.Initially the Terab folder holds 7 jar files which i had decompiled using JD compiler and placed the unzipped 7 folders (which contains the java files ).Now i have imported the HEC project into Eclipse using New ->Project ->Java Project.after importig it throwed me an error saying missing jar files.again i copied the jar files and placed inside Terab folder with other 7 folder.
    Now How i can compile the java files and convert in to class files.Then after compiling the files i will again need to jar all the 7 folder.
    Please tell me the steps i need to follow.How to write an build.xml file ? where i should keep it ? only one build.xml file is enough or should i write 7 build.xml file for each folder ? Please help me out...
    Thanks & Regards
    Kar1983

    put it another way, what I am trying to do is to compile David Brackeen's ch 18 code from his book. The java sourse files can be downloaded here:
    http://www.brackeen.com/javagamebook/
    my question is that how would I complie all of these file so that I can get the program in ch18src\src\com\brackeen\javagamebook\test\ to run?

  • How to compile .java to .class in .jar file

    Hey. I have code to make a .jar file, read .java files, and save them as .class files in the .jar file. When I open the .jar file, it says that the magic numbers on the classes are wrong. So I figured that Java must compile the .java files to .class files in bytecode.
    Question: What's the code to compile a string from a .java file to a .class file?
    Here's my code:
    try {
                // Name of jar file to write
                String archiveFile = Name + ".jar";
                Manifest jman = new Manifest();
                try {
                    // Create a manifest from a file
                    //InputStream fis = new FileInputStream("manifestfile");
                    //Manifest manifest = new Manifest(fis);
                    // Construct a string version of a manifest
                    StringBuffer sbuf = new StringBuffer();
                    sbuf.append("Manifest-Version: 1.0\n");
                    sbuf.append("Ant-Version: Apache Ant 1.7.1\n");
                    sbuf.append("Created-By: 1.5.0_19-137 (Apple Inc.)\n");
                    sbuf.append("Main-Class: Main\n");
                    sbuf.append("Class-Path: lib/swing-layout-1.0.3.jar\n");
                    sbuf.append("X-COMMENT: Main-Class will be added automatically by build\n");
                    // Convert the string to a input stream
                    InputStream is = new ByteArrayInputStream(sbuf.toString().getBytes("UTF-8"));
                    // Create the manifest
                    jman = new Manifest(is);
                } catch (IOException e) {
                FileOutputStream stream = new FileOutputStream(archiveFile, true);// archive file is jar file name
                JarOutputStream out = new JarOutputStream(stream, jman);
                out.putNextEntry(new JarEntry("Main.class"));
                StringBuffer sbuf = new StringBuffer();
                sbuf.append(readTextFromJar("Main.txt")));
                out.write(sbuf.toString().getBytes("UTF-8"));
                out.closeEntry();
                out.putNextEntry(new JarEntry("MainScreen.class"));
                sbuf = new StringBuffer();
                sbuf.append(readTextFromJar("MainScreen.txt"));
                out.write(sbuf.toString().getBytes("UTF-8"));
                out.closeEntry();
                out.putNextEntry(new JarEntry("GCanvas.class"));
                sbuf = new StringBuffer();
                sbuf.append(readTextFromJar("GCanvas.txt"));
                out.write(sbuf.toString().getBytes("UTF-8"));
                out.closeEntry();
                out.close();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.toString(), "BUG!", JOptionPane.INFORMATION_MESSAGE);
                ex.printStackTrace();
            }Thanks,
    -Gandolf

    So I'm guessing that none of you guys have the knowledge on how to compile a java application within a java application. I was thinking that it had something to do with javac... but I'm unsure.
    If no one can answer the question, could someone point me to an expert who would know?
    -Gandolf

  • Using JavaCompiler Class for Debugging Info Only

    Hello everyone,
    Before I get started into the problem, I'll tell you what it is I'd like to do. I'm building an educational applet that'll allow students learning Java programming to write code on a Web page. My goal is to simulate a compiler environment without having it actually compile code (i.e. I want to tell them if there are any syntactic errors in their code). I've searched around the Web quite a bit for how to do this, and I thought I had something by using the JavaCompiler class. It works perfectly in a command-line version I've developed, but in the applet, when I invoke the compiler, the applet freezes. I've isolated it to the compiler call itself. Here is the init method (yes, I know it's a better idea to do the hard work and GUI building in a separate class; but right now, I'm just checking if it all works).
    @Override
    public void init()
    output = new JTextArea(5, 30);
    this.getContentPane().add(output);
    PrintWriter out = new PrintWriter(new TextAreaWriter(output));
    out.print("Hello!");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    String program = "class Test{" + " public static void main (String [] args){"
    + " System.out.printl (\"Hello, World\");"
    + " System.out.println (args.length);" + " }" + "}";
    Iterable<? extends JavaFileObject> fileObjects;
    fileObjects = getJavaSourceFromString(program);
    compiler.getTask(null, null, null, getOptions(), null, fileObjects).call();
    If I exclude the bold line of code, the applet runs. Otherwise it hangs and does nothing. I imagine this has something to do with the execution environment, permissions, etc. If you'd like to see more of the code I'm using, let me know.
    My questions are these: is there an easier way to go about this? Is there a way to invoke the compiler to get its output only, WITHOUT directly compiling a class? Is there a Magic Library designed for this that I've somehow overlooked? I know JDB only works on already-compiled class files; there's a tool called Checkstyle that seems to be more for formatting and subtle issues of style (hence, the name) than actual error checking (not to mention, it requires compiled code as well).
    Any thoughts would be greatly appreciated, all. :) Let me know if you need more info.

    >
    I checked the console after the freeze; it's handing me a NullPointerException for that line, which would be understandable except all of the arguments to call() can deal with null values. ( http://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html )
    From the javadoc for ToolProvider.getSystemJavaCompiler():
        Returns:
            the compiler provided with this platform or null if no compiler is providedSo it's definitely possible that compiler.getTask(null, null, null, getOptions(), null, fileObjects) returns null.
    Indeed that's what I would expect from a browser's JVM (which includes only a JRE, and not a JDK).
    Edited by: jduprez on Apr 29, 2011 2:56 PM
    Ah, ah, I missed your latest edit while I was reading the API Javadoc :o)
    Glad you found out!

  • How to compile package which contain class outside the package

    I am writing a JDBC driver.
    I have the following package structure in the folder:
    MyDriver
        |_manager.jar
        |_com
               |_ jdbc
                       |_ HXDriver
                       |_ HXConnection
                       |_ HXResultSet
                       |_ HXStatementIn manager.jar, there is a remote object Interaface(Manager.java) which I need to use inside HXConnection.
    My question is how to compile(or/and how to set the classpath)so that I can compile the 4 classes inside jdbc package.
    I tried this:
    C:\MyDriver>javac -cp .;manager.jar com/hx/jdbc/*.java
    However, this does not work, compiler says it cannot find Manager
    Please help me.
    Cheers

    D:\380 Project\Driver>javac -cp .;manager.jar com\hx\jdbc\*.java
    com\hx\jdbc\HXConnection.java:21: cannot find symbol
    symbol  : class Manager
    location: class com.hx.jdbc.HXConnection
            private Manager manager;
                    ^
    com\hx\jdbc\HXStatement.java:18: cannot find symbol
    symbol  : class Manager
    location: class com.hx.jdbc.HXStatement
            private Manager manager;
                    ^
    com\hx\jdbc\HXStatement.java:20: cannot find symbol
    symbol  : class Manager
    location: class com.hx.jdbc.HXStatement
            public HXStatement(Manager manager){
                               ^
    com\hx\jdbc\HXConnection.java:41: cannot find symbol
    symbol  : class Manager
    location: class com.hx.jdbc.HXConnection
                            manager = (Manager)reg.lookup("manager");
                                       ^

  • Newbie question: how to compile servlet using tomcat?? Thank you

    How to set classpath? How to compile servlet.java?

    jsp is also converted into a servlet .java nd then into a class file
    this is index.jsp
    <%@ page contentType="text/html;charset=windows-1252"%>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <title>untitled</title>
      </head>
      <body>
      </body>
    </html>this is _index.java
    /*@lineinfo:filename=/index.jsp*/
      /*@lineinfo:generated-code*/
    import oracle.jsp.runtime.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.jsp.*;
    public class _index extends com.orionserver.http.OrionHttpJspPage {
      public final String _globalsClassName = null;
      // ** Begin Declarations
      // ** End Declarations
      public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException {
        response.setContentType( "text/html;charset=windows-1252");
        /* set up the intrinsic variables using the pageContext goober:
        ** session = HttpSession
        ** application = ServletContext
        ** out = JspWriter
        ** page = this
        ** config = ServletConfig
        ** all session/app beans declared in globals.jsa
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext( this, request, response, null, true, JspWriter.DEFAULT_BUFFER, true);
        // Note: this is not emitted if the session directive == false
        HttpSession session = pageContext.getSession();
        if (pageContext.getAttribute(OracleJspRuntime.JSP_REQUEST_REDIRECTED, PageContext.REQUEST_SCOPE) != null) {
          pageContext.setAttribute(OracleJspRuntime.JSP_PAGE_DONTNOTIFY, "true", PageContext.PAGE_SCOPE);
          JspFactory.getDefaultFactory().releasePageContext(pageContext);
          return;
        int __jsp_tag_starteval;
        ServletContext application = pageContext.getServletContext();
        JspWriter out = pageContext.getOut();
        _index page = this;
        ServletConfig config = pageContext.getServletConfig();
        try {
          // global beans
          // end global beans
          out.write(__oracle_jsp_text[0]);
        catch( Throwable e) {
          try {
            if (out != null) out.clear();
          catch( Exception clearException) {
          pageContext.handlePageException( e);
        finally {
          OracleJspRuntime.extraHandlePCFinally(pageContext,false);
          JspFactory.getDefaultFactory().releasePageContext(pageContext);
      private static final char __oracle_jsp_text[][]=new char[1][];
      static {
        try {
        __oracle_jsp_text[0] =
        "\n<html>\n  <head>\n    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">\n    <title>untitled</title>\n  </head>\n  <body>\n  </body>\n</html>\n".toCharArray();
        catch (Throwable th) {
          System.err.println(th);
    }as you can see.. my IDE converts it into a java class so it can be conpiled to a class file.. by the way i use Oracle Jdeveloper 10g for this pupose of showing you what is happening to your jsp

  • How to compile java programs in j2EE 1.4 SDK

    hi,
    i HAVE JUST INSTALLED NEW J2EE 1.4 SDK , IT HAS BEED INSTALLED SUCCESFULLY BUT I AM UNABLE TO COMPILE JAVA PROGRAMS WHICH I USED TO RUN IN SDK 1.4 ,OR EVEN NEW WRITTEN EXAMPLES. CAN ANYONE PLZ HELP ME.

    J2EE by itself is not capable of compiling Java. It requires that a J2SDK be installed first - this is what compiles and runs Java programs. Did you install the combination J2SDK and J2EE, or just the J2EE?
    If both are installed, then you should be able to compile and run as you used to..

  • Has anybody noticed how much RAM Java uses?

    Hi Everyone,
    I have been playing around a little with Java programs, and far out the RAM in my computer gets strained!!! I don't know how many times a Java application has completely locked down my 667MHz, 320Mb computer. My brothers 1.2GHz, 256Mb runs Java a little better, but really to play "hard ball" Java style you would need a 2.4GHz Pentium 4 with between 512 and 1024MB of RAM.
    Obviously Sun Microsystems have looked to the future with Java. They have played their cards very well by creating a programming language that is a little hard for current computer hardware to run.
    In ten years time when we are talking about computer hardware, we will have hard drives with terabytes of space sitting on our home PC, don't worry about clock speeds, there won't be any, the Quantum computer has already taken care of that (for all those novice Quantum Guru's out there - information exchange takes place in no time, that is not faster than the speed of light... the messages simply takes place in no Time.). Technology moves so fast that it is hard to keep pace, unless of course you are addicted to Reading!!
    At the moment we obviously do not have the hardware to run massive Java applications. So instead we have garbage collection. How effective is garbage collection, and what can be done to improve it?
    I have read a little about garbage collection, but it sounds quite haphazard, possibly unreliable. Obviously object orientated code takes up a lot of memory, by learning garbage collection techniques I hope to improve my coding. If anybody who reads this thread can contribute anything of personal experience related to garbage collection, it will be greatly appreciated. Code is always good, but I am also looking for peoples ideas about improving garbage collection, even if those ideas are not viable in the current version of the JDK.
    Thanks for your comments and I hope that you enjoyed reading this thread.
    David

    Hi,
    if it was meant as a joke, I enjoyed it - but if your opinion is really that of java, you have posted, I would suggest to read some of the documentations provided by Sun and you will find out, how java uses memory and you will also find out, that garbage collection is not the point, you have to worry about, because it is automatically done by the JVM. Also javac has parameters, where you can manipulate the memory usage of the JVM. So, please start reading in the case this was not just a joke :)
    greetings Marsian

  • How to Compile java project on command prompt

    Hello Friends,
    I have created one java project in eclipse. It has 3 packages, 4 external jars and one Link source (meaning it uses other java package that is not in the same project folder)
    It runs perfectly using eclipse.
    Now I want to compile my project and want to run that project.
    I tried using "javac -classpath........." but it didn't work for me. Here is the command I used:
    I am running this command under my main project folder
    javac -classpath ./../../../lib/tools/lib/blur/blur_formats-1.0.jar;./../lib/commons-codec/commons-codec-1.3.jar;./../lib/commons-httpclient/commons-httpclient-3.1.jar;./../lib/commons-logging/commons-logging-1.1.1.jar;./../lib/org.json/org.json.jar;./../lib/smack/3_0_4/smack.jar;./../../../device/branches/viper/Service/blur/common/push/src* ./src/com.proj.hnm.push.StartService.java*
    1) /device/branches/viper/Service/blur/common/push/src - is a different package I am referring (not in my current project folder) - it has java files in com.pushsync package
    2) ./src/com.proj.hnm.push.StartService.java is my main class, com.proj.hnm package also contains another 2 package, and those other packages also have .java files
    Please tell me how do I run my java project?
    Thanks

    Hi
    Since it works fine in Eclipse you should install the [Fat Jar eclipse plugin|http://fjep.sourceforge.net/] which will pack everything thats in your eclipse project into a single jar file. Then you can run: java -jar myProject.jar and it should work.

  • How to compile .java files in windows server

    Hi All,
    I want to compile my CO.java file in server directly how can i do that my server is windows server
    If it is Linux i can login through putty and go to java top and then file location then i use to do javac filename.java then i use to get filename.class but now same thing i did in windows server which is not working please sugget how to do its bit urgent.

    Why do you want to compile it on the server and not in jdeveloper? You should be able to issue the javac command from the prompt. Your unix account must have permissions to that command though.
    For more info on the javac command:
    http://download.oracle.com/javase/1.4.2/docs/tooldocs/windows/javac.html
    Kristofer Cruz

  • How to compile & run using command prompt

    Hi all,
    I have a java application consisting of 3 packages & a jar file in the following hierarchy:
    -Project
    -classes
    -src
    -package1
    -package2
    -package3
    -file.jar
    The main class exists in package2 and uses classes within file.jar
    I want the steps to compile and execute the project using command prompt in windows such that the generated classes will be saved in the classes directory
    Can anyone help?
    Thanx in advance

    Hey,
    If your source(*.java) files are in src folder and ur currnet directory is project
    and you want all your class files to be classes folder then you can try this :
    c:\project>javac -cp src\file.jar -d classes\ src\*.javaAssuming that your file.jar file is in src folder.
    The above command will set the classpath to src\file.jar (-cp src\file.jar)
    -d classes\ - will generate all your class files with package hierarchy if any into classes directory.
    src\*.java - specifies the files to be compiled.
    Hope this helps.

  • How to compile java servlet

    this the error i encounter.. i have read some of the posted topics on it but i dont understand how i can create my own classpath..where should i do that..what should i write...how i have to save it...pls help me...
    C:\currentyaazmin1\java>javac login2.java
    login2.java:9: Package javax.servlet.http not found in import.
    import javax.servlet.http.*;
    ^
    login2.java:11: Package javax.servlet not found in import.
    import javax.servlet.*;
    ^
    login2.java:16: Superclass HttpServlet of class login2 not found.
    public class login2 extends HttpServlet
    ^
    3 errors
    i have already installed jdk1.3 an jsdk2.1...i also copied javax folder from jsdk2.1 and pasted in c:....still i encouter the same thing... pls help

    Download j2ee is recommended to solve any compling such as servlets and swing
    http://java.sun.com/j2ee/download.html
    Once done all you do is include j2ee.jar and you have xml, servlets, rmi the works!! :)
    However since you download the servelet component only, search in you hard drive for ".jar" file.
    You can open the .jar file with a WinZip and you can check if it as javax.servlet.http.* by looking at the far right for javax/servlet/http
    Once you know the jar file to include. Next is to put it in the classpath. The most simple way using NT example, how Windows 95/98 is similar. Go to:
    Control Panel -> Double Click on System -> Click on Environment tab
    Type below in Variable: CLASSPATH
    Type in Value: PATH TO SERVLET;.;
    Don't forget the ;.; (the dot for currnet path to run)
    If you need to add more to the classpath, seperate by classpath.
    Log off and log back in as your user. No need to reset the machine.
    The system will pick the new CLASSPATH.
    Test on dos as "echo %CLASSPATH%" to see what its set to.

Maybe you are looking for