Monday, August 6, 2018

Jython and the Java main()

hello all,

A quick post for today:

Have you exprienced frustration at attempting to run a Java main() method from Jython?

The reason is simple: Jython follows mos of the rules of Java, but not all. When you call Java's main() method using Java, you don't need to pass in anything.

However, when doing this from Jython, it complains. Even if you have arguments to pass it complains. Why? Because Java expects a String[] array. Java things you're passing an empty string, which from Java is fine, If you have arguments, you need to put the arguments into a list, and pass the list and Java will accept it.

Here is a simple Java code demonstrating printing from the console via Java. The example if from the book Java: The Complete Reference, 10th Edition,  by Herbert Schildt:

=====================BRRead.java=========

import java.io.*;

public class BRRead {
    public static void main(String[] args) {

        char c;

        BufferedReader br =
                new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter characters. 'q' to quit.");
        try {
            do {
                c = (char) br.read();
                System.out.print(c);

            } while (c != 'q');
        } catch (IOException e) {
            System.out.println("Exception");
        }
    }
}

==========End of file==========


Go to the directory where the .class file is saved, and fire up your Jython
interpreter.

Type the follwoing:

br = BRRead()

This will create an object that references the class. Now, create an array:

foo = []

It's acceptable to pass an empty list. It makes Java happy. If your main() requires arguments, then create the list as above, with your arguments as strings. To ensure you can see main from Jython, do dir(br).

If you do, you're ready to run the main() method.

br.main(foo)

You will see the two lines, with the press 'q' to stop. Type away. When you're done, type q by itself to go back to the interpreter prompt.

It may appear to be a flaw in Jython, but you have this work around to see if your code works as it should from Jython.

If you have any questions, please ask.

Happy coding!

1 comment:

  1. Useful in cases where you must run the main(), such as when doing a self-test.

    ReplyDelete