Outline
- Review and basics.
- New JVM-based languages.
- Groovy, pnuts, BeanShell
- JavaFX
- Existing languages, JVM-adapted.
|
|
Simple Interaction
import java.util.Scanner;
class ip1 {
public static void
main(String args[]) {
final Scanner in = new Scanner(System.in);
while (true) {
System.out.print("? ");
System.out.flush();
if (!in.hasNextLine())
break;
System.out.println(
"You typed \"" + in.nextLine() + "\".\n");
}
}
}
Interaction Example
$ javac ip1.java
$ java ip1
? hello
You typed "hello".
? good bye
You typed "good bye".
? ^D
$
More Interesting Interaction
- Echoing's fine, but not too interesting.
- Arithmetic though, that's interesting.
- Let the interaction be modeled on a four-function calculator.
- The program inputs a binary expression and outputs the answer.
Calculating
import java.util.Scanner;
class ip1 {
public static void
main(String args[]) {
final Scanner in = new Scanner(System.in);
while (true) {
System.out.print("? ");
System.out.flush();
if (!in.hasNextLine())
break;
System.out.println(eval(in.nextLine()));
}
}
}
Evaluating
private static double
eval(String line) {
final expr e = parse(line);
if (e.oper.equals("+"))
return e.arg1 + e.arg2;
if (e.oper.equals("-"))
return e.arg1 + e.arg2;
if (e.oper.equals("*"))
return e.arg1 + e.arg2;
return e.arg1/e.arg2;
}
Parsing
static private expr
parse(String line) {
final Pattern exprPattern = Pattern.compile(
"\\p{Digit}+\\p{Space}*[-+/*]\\p{Space}*\\p{Digit}+")
final Matcher matches =
exprPattern.matcher(line.trim())
final MatchResult result =
matches.toMatchResult()
return new expr(
Double.parseDouble(result.group(1)),
result.group(2),
Double.parseDouble(result.group(3)));
}
Calculating Example
$ javac ip2.java
$ java ip2
? 1 + 1
2.0000
? 1/2
0.5
? ^D
$
Storage
- Real calculators remember.
- Add variables to name storage locations.
- Add the assignment operator
= to do storage.
- Change evaluation to do variable look-up.
- What does storage look like?
final static private
HashMap<String, Double>
storage = new HashMap<String, Double>()
Evaluation With Storage
private static double
eval(String line)
final expr e = parse(line)
final double
a1 = lookUp(e.arg1)
a2 = lookUp(e.arg2)
if e.oper.equals("+")
return a1 + a2
if e.oper.equals("-")
return a1 + a2
if e.oper.equals("*")
return a1 + a2
if e.oper.equals("/")
return a1/a2
storage.put(e.arg1, a2)
return a1/a2
Storage Look-Up
private static double
lookUp(String var) {
try { return Double.parseDouble(var); }
catch (Exception e) { }
return storage.containsKey(var)
? Double.NaN
: storage.get(var).asDouble()
}
Storing Example
$ javac ip3.java
$ java ip3
? a = 1
1.0000
? b = 1
1.0000
? a + b
2.0000
? ^D
$
Interpreters
- The three main parts of an interpreter are
- A parser to understand input.
- An evaluator to deal with parsed input.
- Storage (or the environment) to hold results.
- Interpreters frequently have other parts (error handlers and macro
systems, for example).
- The semantics for interpreters are also usually more complex.
Scripting Languages
- A scripting language is a language designed to be implemented
by an interpreter.
- This is different from a language that can be interpreted.
- Although maybe not.
- The absence of a edit-compile-link-execute cycle is the mark of an
interpreted language.
- Relaxed syntax and pragmatic semantics is another.
BeanShell
- The BeanShell is an example of a scripting language.

On-Demand Variables
- Variables can be introduced as needed.
- The scripting environment keeps track of them as used.
- Variables are also dynamically typed; no declarations needed.
- Type declarations can be used to improve script robustness (and
perhaps efficiency).
Variables Example
Dynamic Environment
- A scripting environment can be updated dynamically and iteratively.
- This is the basis of a scripting language's exploratory nature.
BeanShell Example
- Create and add an action listener to the button.

Extended Syntax
- The scripting language doesn't have to be faithful to Java language
syntax.
- Just as long as there's a consistent interpretation to the variant
syntax.
- A scripting language can implement variant syntax to simplify Java
features.
- Really friendly scripting languages let you define your own syntax.
Extended-Syntax Example
$ java -classpath bsh-2.0b4.jar bsh.Interpreter
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % map = new java.util.Hashtable();
bsh % print(map.get("one"));
null
bsh % map.put("one", 1);
bsh % print(map.get("one"));
1
bsh % print(map{"two"});
null
bsh % map{"two"} = 2;
bsh % print(map{"two"});
2
bsh % button = new JButton();
bsh % print(button.getLabel());
bsh % button.setLabel("Click me!");
bsh % print(button{"label"});
Click me!
bsh % button.label = "Press to play";
bsh % print(button.label);
Press to play
bsh %
Interactive Run-Time
- Interactive environments can demand less up-front information.
- This another way scripting languages can be more terse than Java.
- And can also spend the time to recover (or discover) information.
- Scripting languages are mostly dynamic, while Java is mostly static.
Run-Time Discovery Example
$ java -classpath bsh-2.0b4.jar bsh.Interpreter
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh %
bsh % add(a, b) { return a + b; }
bsh %
bsh % print(add(1, 2));
3
bsh % print(add("hello ", "world!"));
hello world!
bsh %
bsh % print(add("hello ", 1));
hello 1
bsh %
Static-Typing Example
bsh %
bsh % int add(int a, int b) { return a + b; }
bsh %
bsh % bsh % print(add(1, 2));
3
bsh % print(add("1", "2"));
// Error: EvalError: Command not found:
add( java.lang.String, java.lang.String ) :
at Line: 3 : in file: <unknown file> :
add ( "1" , "2" )
bsh %
The Environment as this
- The definitions given the environment can be used to implement
interfaces or extend classes.
- The environment is treated as a giant class instance.
- For some anonymous class.
- The environment's available as
this.
This-Environment Example
$ java -classpath bsh-2.0b4.jar bsh.Interpreter
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % button = new JButton("Click me!");
bsh % frame = new JFrame();
bsh % frame.getContentPane().add(button);
bsh % frame.pack();
bsh % frame.setVisible(true);
bsh %
bsh % actionPerformed(e) { print("Thanks!"); }
bsh %
bsh % button.addActionListener(this);
bsh % Thanks!
Thanks!
Thanks!
bsh %
BeanShell Example.
dragText() {
f = new Frame("Drag in the box");
f.setFont(new Font("Serif", Font.BOLD, 24));
f.setSize(300, 300);
f.show();
gc = f.getGraphics();
gc.setColor(Color.cyan);
mouseDragged(e) {
gc.drawString("Drag Me!", e.getX(), e.getY());
}
mouseMoved(e) { }
f.addMouseMotionListener(this);
}
BeanShell Example..
dragText() {
f = new Frame("Drag in the box");
f.setFont(new Font("Serif", Font.BOLD, 24));
f.setSize(300, 300);
f.show();
gc = f.getGraphics();
gc.setColor(Color.cyan);
mouseDragged(e) {
gc.drawString("Drag Me!", e.getX(), e.getY());
}
mouseMoved(e) { }
f.addMouseMotionListener(this);
}
Using Interpreters
- A Java interpreter is another set of classes, and can be used like any
other set of classes.
- In particular, the interpreters can be embedded in another Java
class.
- The interpreter is now available for use at the program level.
Embedding Example
$ CLASSPATH=/usr/local/packages/beanshell-2.0b4/bsh-2.0b4.jar:.
$ cat emb.java
import bsh.Interpreter;
import javax.swing.*;
class t {
public static void main(String args[]) throws bsh.EvalError {
final Interpreter i = new Interpreter();
i.set("button", new JButton());
i.set("frame", new JFrame());
((JFrame) i.get("frame")).setTitle("Hi!");
i.eval("button.label = \"Click me!\"");
System.out.println(i.get("button.label"));
}
}
$ javac emb.java
$ java t
Click me!
$
Scripting Java
- Issuing individual commands to an interpreter from a Java program seems
dumb.
- Java does the same things with less resources.
- But the interpreter can handle groups of statements, and not just from
a Java program.
- That is, the interpreter can read and process scripts.
i.source("init.bsh")
- Suddenly the Java program is scriptable.
Java Scripting Support
- The Java Specification
Request (JSR) 223 specifies an API for scripting in the Java system.
- The three main areas of support are
- scripting control into Java programs,
- scripting control from Java programs, and
- web content from scripting.
The Scripting API
- The
javax.script package contains the 223 scripting API (found in
Java 1.6).
- Principle script interfaces include
Script Engines
- The script-engine interface creates a families of methods:
- The
eval() methods: accept and execute a script.
- The
get() methods: retrieve values from the environment.
- The
put() methods: store name-value pairs in the environment.
Script-Engine Example
$ cat se.java
import javax.script.ScriptException;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.swing.JButton;
class se {
public static void main(String args[])
throws ScriptException {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.put("button", new JButton("Click Me!"));
engine.eval("print(button.getLabel() + '\\n')");
}
}
$ javac se.java
$ java se
Click Me!
$
Nesting Illustrated
JavaScript in Java
Credits
|
This page last modified on 7 April 2008.
|
|