Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6781931
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T16:40:54+00:00 2026-05-26T16:40:54+00:00

I have found many references explaining how to programmatically compile a Java class using

  • 0

I have found many references explaining how to programmatically compile a Java class using the JavaCompiler class:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, "a_file_name");

However, I would like to know if there is an open source library that let me compile source code generated programmatically (therefore without a src file being involved) and generate some byte code in an output stream (without generating a class file in the file system).

For example, I am looking for being able to write something like this:

InputStream input = generateSourceCode();
OutputStream output = getByteCode(input);
doCoolStuffWithByteCode(output);

Thanks for any help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T16:40:55+00:00Added an answer on May 26, 2026 at 4:40 pm

    To start, look at the JavaCompiler API. Basically:

    1. Create the Java class in a string.
    2. Put the string into class that extends SimpleJavaFileObject.
    3. Compile using a JavaCompiler instance.

    Finally, call the methods the new class.


    Here is an example that works with JDK6+:

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.lang.reflect.InvocationTargetException;
    import java.net.URI;
    import java.util.Arrays;
    
    import javax.tools.Diagnostic;
    import javax.tools.DiagnosticCollector;
    import javax.tools.JavaCompiler;
    import javax.tools.JavaFileObject;
    import javax.tools.SimpleJavaFileObject;
    import javax.tools.ToolProvider;
    import javax.tools.JavaCompiler.CompilationTask;
    import javax.tools.JavaFileObject.Kind;
    
    public class CompileSourceInMemory {
      public static void main(String args[]) throws IOException {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    
        StringWriter writer = new StringWriter();
        PrintWriter out = new PrintWriter(writer);
        out.println("public class HelloWorld {");
        out.println("  public static void main(String args[]) {");
        out.println("    System.out.println(\"This is in another java file\");");    
        out.println("  }");
        out.println("}");
        out.close();
        JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());
    
        Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
        CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
    
        boolean success = task.call();
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
          System.out.println(diagnostic.getCode());
          System.out.println(diagnostic.getKind());
          System.out.println(diagnostic.getPosition());
          System.out.println(diagnostic.getStartPosition());
          System.out.println(diagnostic.getEndPosition());
          System.out.println(diagnostic.getSource());
          System.out.println(diagnostic.getMessage(null));
    
        }
        System.out.println("Success: " + success);
    
        if (success) {
          try {
            Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class })
                .invoke(null, new Object[] { null });
          } catch (ClassNotFoundException e) {
            System.err.println("Class not found: " + e);
          } catch (NoSuchMethodException e) {
            System.err.println("No such method: " + e);
          } catch (IllegalAccessException e) {
            System.err.println("Illegal access: " + e);
          } catch (InvocationTargetException e) {
            System.err.println("Invocation target: " + e);
          }
        }
      }
    }
    
    class JavaSourceFromString extends SimpleJavaFileObject {
      final String code;
    
      JavaSourceFromString(String name, String code) {
        super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
        this.code = code;
      }
    
      @Override
      public CharSequence getCharContent(boolean ignoreEncodingErrors) {
        return code;
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have found many tutorials about using Windows Server 2003 as a development machine,
I have found many references to this term on the web, especially on Microsoft's
I have found many people with simliar issues but no soultions...basically I have two
Wondering how to open many new windows with Javascript. I have found plenty of
This is something I've pseudo-solved many times and have never quite found a solution
I found this: http://msdn.microsoft.com/en-us/library/vslangproj80.reference3%28VS.80%29.aspx what I have in mind is that many of the
Using Mongoid, let's say I have the following classes: class Map include Mongoid::Document embeds_many
I have a Rotation class, which contains references to multiple lists of Advert objects.
I have found some in the Cappuccino website (vim, textmate and SubEthaEdit), but not
I have found that my HTML is, to be honest, very clunky. Small, simple

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.