954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Making A Java Compiler... In Java

Hi,

Is it possible to create a Java compiler? Could you make a Notepad-like application, save the code as a .java file, compile it into a .class file, and run it? Basically, I want to combine Notepad and Command Prompt. I just need help on the compiling part (and listing the errors, if any).

Thanks in advanced for your help.

Ghost
Posting Whiz
352 posts since Aug 2004
Reputation Points: 12
Solved Threads: 2
 

hi,
I had once made a full fledge editor for java in java. All i did was to include the classpath while issuing the javac command.

I used
Process process=Runtime.getRuntime().exec("javac -cp ");
then I used err stream and output stream to read the output.
The same i used for java command as well.

regards
srinivas

cheenu78
Light Poster
45 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

To run a class you don't need to launch the java executable.
Create a classloader and use that to fork off the class in-process :)

You can also do that to compile classes. Simply hook into Ant which is a Java application and can compile Java classes for you (by hooking into the JDK).
Examining the Ant source should be interesting (I've not yet done so) to see how they do it in a platform independent way.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

thanks guys!

jwenting - WHOA!!!!!!!! You're approach is really confusing! I think I'll stick with the other method but thanks for your reply.

cheenu78 - thanks! can u explain how to get the error messages a little more. Thanks again.

Ghost
Posting Whiz
352 posts since Aug 2004
Reputation Points: 12
Solved Threads: 2
 

confusing? It's what I'd do. It's platform independent which is important as I work on several operating systems at the same time (Windows, 2 versions of Linux, and AIX, and I hope to add a Mac sometime next year).
And calling Ant should be rather easy. probably easier in fact than capturing the commandline output.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

would you mind explaining how to use Ant then??

Thank you very much for your help.

Ghost
Posting Whiz
352 posts since Aug 2004
Reputation Points: 12
Solved Threads: 2
 

Ant is a tool similar to make (which is for C/C++ mainly).
It's written completely in Java so can easily integrate with Java applications.

There's books written about it, I'm barely scratching the surface by using it from the commandline to compile and package my projects.
Maybe next year when I may have time to do more I'm going to really dive into it :)

http://ant.apache.org

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

Hi!

I started to make the compiler but I have some problems. First, it won't compile. Second, I can't get the error messages/output to appear. My code is below. Thanks in advanced for your help.

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class JEdit extends JFrame implements ActionListener
{

  JButton open = new JButton("Open");
  JButton save = new JButton("Save");
  JButton compile = new JButton("Compile");
  JButton run = new JButton("Run");
  JButton help = new JButton("Help");

  JTextArea code = new JTextArea("",28,65);
  JTextArea output = new JTextArea("",7,65);

  File fileS = null;

  Font cf = new Font("monospaced",Font.PLAIN,12);

  public JEdit()
  {
    super("Java CinnaComp");
    setSize(500,710);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    Container contentArea = getContentPane();
    contentArea.setBackground(Color.lightGray);

    FlowLayout flowManager = new FlowLayout();
    contentArea.setLayout(flowManager);

    contentArea.add(save);
    save.addActionListener(this);
    contentArea.add(open);
    open.addActionListener(this);
    contentArea.add(compile);
    compile.addActionListener(this);
    contentArea.add(run);
    run.addActionListener(this);
    contentArea.add(help);
    help.addActionListener(this);
    JScrollPane scrollPane = new JScrollPane(code,
                                             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    contentArea.add(scrollPane);
    code.setFont(cf);
    JScrollPane scrollPane2 = new JScrollPane(output,
                                             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    contentArea.add(scrollPane2);
    output.setFont(cf);


    setContentPane(contentArea);
  }

  public void actionPerformed(ActionEvent event)
  {
    if(event.getSource() == save)
    {
      JFileChooser saveChooser = new JFileChooser();
      saveChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      int result = saveChooser.showSaveDialog(this);
      if(result == JFileChooser.CANCEL_OPTION)
        return;
      fileS = saveChooser.getSelectedFile();
      if(fileS == null || fileS.getName().equals(""))
        JOptionPane.showMessageDialog(null, "Invalid File Name",
                    "Invalid File Name", JOptionPane.ERROR_MESSAGE);
      else
      {
        try
        {
          FileWriter saveFile = new FileWriter(fileS.getPath());
          BufferedWriter bufferS = new BufferedWriter(saveFile);
          bufferS.write(code.getText());
          bufferS.close();
        }
        catch (Exception e1)
        {
        }
      }
    }

    if(event.getSource() == open)
    {
      JFileChooser openChooser = new JFileChooser();
      openChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      int result2 = openChooser.showOpenDialog(this);
      if(result2 == JFileChooser.CANCEL_OPTION)
        return;
      File fileO = openChooser.getSelectedFile();
      if(fileO == null || fileO.getName().equals(""))
        JOptionPane.showMessageDialog(null, "Invalid File Name",
                    "Invalid File Name", JOptionPane.ERROR_MESSAGE);
      else
      {
        try
        {
          FileReader openFile = new FileReader(fileO.getPath());
          BufferedReader bufferO = new BufferedReader(openFile);
          String textline = null;
          while((textline = bufferO.readLine()) != null)
          {
            code.append(textline+"\n");
          }
          bufferO.close();
        }
        catch (Exception e2)
        {
        }
      }
    }

    if(event.getSource()==compile)
    {
      try
      {
        Process compile = Runtime.getRuntime().exec("javac -cp " +
            fileS.getPath());
        output.setText(compile.getErrorStream().toString());
      }
      catch(Exception e3)
      {
        output.append("\n"+e3.toString());
      }
    }

    if (event.getSource() == run) {
      try {
        Process run = Runtime.getRuntime().exec("java -cp " +
            fileS.getParent()+fileS.getName());
        output.setText(run.getErrorStream().toString());
        output.append("\n"+run.getOutputStream().toString());
      }
      catch (Exception e4) {
        output.append("\n" + e4.toString());
      }
    }

  }


  public static void main (String [] args)
  {
      new JEdit();
  }
}
Ghost
Posting Whiz
352 posts since Aug 2004
Reputation Points: 12
Solved Threads: 2
 

Just using ant is not too hard, you run the "ant" command from a directory that has a build.xml file. Constructing the build.xml file to do what you want is a little more complex. There are many tutorials to do that. Like this one

http://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/ant/ant.html

JeffHeaton
Junior Poster in Training
58 posts since Jul 2005
Reputation Points: 12
Solved Threads: 0
 

The trick is building the xml file to have ant do tricks like run unit tests, deploy your application to a J2EE server, and things like that :)

And of course integrating Ant inside another application is a bit more involved than just calling the command from the prompt.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

Hi everyone,

jwenting is right. Plug in ant as its more useful and easier and to build an ide is not an easy task. But if you want to still pursue it read up about pipe streams in java. You will also have to use window listeners and not set a default closing for the JFrame.

Richard West

freesoft_2000
Practically a Master Poster
623 posts since Jun 2004
Reputation Points: 25
Solved Threads: 10
 

Of course what he's doing/planning isn't really to make a compiler but to call an external compiler :)

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

true, but can you help me with what i have so far?

thanx.

Ghost
Posting Whiz
352 posts since Aug 2004
Reputation Points: 12
Solved Threads: 2
 

Maybe a bit late, but here's a new article on java.net that does what you're looking for:
http://weblogs.java.net/blog/kirillcool/archive/2005/08/reflection_and.html

The last part is irrelevant as it deals with some obscure XML generation from Java objects, the first part deals with dynamic compilation and classloading.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

Dear Ghost,

I want to make a Java Compiler in Java.

Is it possible to create a Java compiler? Could you

make a Notepad-like application, save the code as

a .java file, compile it into a .class file, and run it?

Basically, I want to combine Notepad and Command

Prompt. I think u have that Code. Please send that

full coding please. Im waiting for ur seen reply.

Thanks in advanced for your help

nmkarthik
Newbie Poster
1 post since Jan 2006
Reputation Points: 10
Solved Threads: 0
 

Hi everyone,

Is it possible to create a Java compiler? Could you make a Notepad-like application, save the code as a .java file, compile it into a .class file, and run it?

It seems you want to create an ide and not a comppiler but the answer is that its possibleBasically, I want to combine Notepad and Command Prompt.

Duly notedI think u have that Code. Please send that full coding please

I doubt he or anyone including myself will send the code.
What you can do is create a topic on creatig an ide by yourself and i'm sure the others will walk you through it if you have specific questions

Here are some tips for you
Runtime
JTextArea
Pipe And Streams

Richard West

freesoft_2000
Practically a Master Poster
623 posts since Jun 2004
Reputation Points: 25
Solved Threads: 10
 

I'll help you with your program, but you need to show some effort! At least create the GUI and TRY to send commands to command prompt. Then I'll be glad to help.

Ghost
Posting Whiz
352 posts since Aug 2004
Reputation Points: 12
Solved Threads: 2
 

Can you help me wlth the following work?:
This sample program shows how to print the current month, now using the "Calendar" object (instead of the Date object which has been deprecated, meaning it has been slated for removal from the language).

// Program prints the current month

import java.util.Calendar;

public class ShowToday {
static String[] monthArray = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

public static void main(String[] args) {
Calendar rightNow = Calendar.getInstance();
int month = rightNow.get( Calendar.MONTH );
// This will be a number from 0 to 11, representing January to December
System.out.println("month: " + month );
// Using the above array, this will print "Jan" thru "Dec"
System.out.println("month: " + monthArray[month] );
}
}
mperkins07
Newbie Poster
5 posts since Apr 2006
Reputation Points: 10
Solved Threads: 0
 

good day to all.
i stumble upon this site because i want to know how to make an interpreter for our project.
we are using jflex as our lexical analyzer.
may i know what's the next step in doing?
thanks

nenbe
Newbie Poster
1 post since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You