#197 Java Scripting

brian Fri 18 Apr 2008

I think one of the next features I'm going to tackle is making Fan more suitable for scripting against Java libraries. We have the native interface now which provides high performance, but is cumbersome to use.

The basic design I'm mulling is:

  • create a new java pod to package up this functionality (we can clone the design for .NET once we are happy)
  • java::Java.make is used to get a handle into a Java environment
  • Java.import lets you add packages
  • Java.trap lets you lookup JClasses
  • JClass.trap lets you lookup static methods/fields
  • JClass.make creates a JObj instance
  • JObj.trap lets you access instance methods/fields
  • Handle the Java bean conventions
  • Allow Funcs to be used as single method interfaces

For my use case, let's start with this little Swing application in Java code:

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

public class Foo
{
  public static void main(String[] args)
  {
    JButton b = new JButton("Hello World");
    b.setForeground(Color.red);
    b.setBackground(Color.yellow);
    b.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent evt)
      {
        System.out.println("Pressed");
      }
    });

    JFrame f = new JFrame("title");
    f.getContentPane().add(b);
    f.setBounds(100, 100, 200, 200);
    f.setVisible(true);
  }
}

It would something like this in Fan using the new java script API:

using java

class Foo
{
  static Void main()
  {
    j := Java.make
    j.import("java.awt")
    j.import("java.awt.event")
    j.import("javax.swing")

    b := j->JButton->make("hello world")
    b->foreground = j->Color->red
    b->background = j->Color->yellow
    b->addActionListener |,| { echo("Pressed") }

    f := j->JFrame->make("title")
    f->contentPane->add(b)
    f->setBounds(100, 100, 200, 200)
    f->visible = true
  }
}

Both Java and JClass would be const so they could be declared as static fields.

Login or Signup to reply.