简体   繁体   中英

Java as a scripting language for Java?

Is it possible to use Java as a scripting language for java? Or maybe somehow compile java scripts into java binarries at runtime? I did tried to search but couldn't find anything comprehensive except for some hacks...

I have experience with other languages and for example for C# I used lua which was quite convenient but now I need to acheive the utmost performance as calls for scripts will be about 1.000.000 per frame.

So I figured that adapting java itself as a scripting language for java program should provide me the best performance and compatibility.

Any suggestions?

BeanShell is a commonly used scripting solution for Java. It's a scripting language which is very Java-like.

Other solutions exist which use the Java infrastructure and JVM, but with a different language. eg Scala, Groovy and Jython (a Java-compatible Python). The important thing to realise with all of these is that they'll interoperate with Java libraries created using standard Java, so you could trivially use (say) Scala to drive your Java-language created solution.

The above all provide a REPL ( read-eval-print-loop ) so you can import, instantiate and interact with your objects in a dynamic command-line environment. That's very useful for testing and prototyping interactions, as well as testing your scripts.

您可以使用BeanShell,但Groovy,XTend和Scala可能会做出更好的选择。

The answer is 'Yes', you can use Java as a scripting language within a Java program itself. In addition, there are several other languages that can also be used for this purpose - Javascript, LUA, Groovy, Ruby, the list is long. Integration has been made much easier with the introduction of the javax.scripting API, which standardizes and greatly simplifies the processing of integrating third party scripting languages into Java programs. I would highly recommend reading up on the API and some tutorials on Oracles page.

http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html

Since version 7.0, Java has "official" support for compiling at runtime (if tools.jar from SDK is on classpath). Probably, the execution speed can be as high as compiled java, higher than interpreters.

Starting point to read (many samples in the internet):

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;


JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(compiler!=null) {
    .... 
}

You can use JANINO http://docs.codehaus.org/display/JANINO/Home ...a light-weight, "embedded" JavaTM compiler that compiles simple programs in memory into JavaTM bytecode which executes within the JVM of the running program... Please see examples http://docs.codehaus.org/display/JANINO/Basic

Or You can use MVEL http://mvel.codehaus.org/ It is similar to BeanShell, but much faster.

For simple stuff when groovy etc is not available I embed java into bash scripts as detailed on project java-script-template . Code looks like this:

#!/bin/bash
set -e
TEMP_DIRECTORY=/tmp
TEMPFILE=`mktemp $TEMP_DIRECTORY/ScriptXXXXX|sed -e 's/\.//g'`
CLASS_NAME=`basename "$TEMPFILE"`
JAVA_SOURCE=$TEMPFILE.java
cat <<EOF >$JAVA_SOURCE.tmp

//Write your java class here with a main method
//Be sure to leave the name of the class as Script 

//import some commonly used imports
import java.io.*;
import java.text.*;
import java.util.*;

public class Script {

    public static void main(String[] args) throws Exception {
       System.out.println("Here's a test run for you");
    }

}

EOF

## change the name of the class to match the file
sed "s/public class Script /public class $CLASS_NAME /g" $JAVA_SOURCE.tmp >$JAVA_SOURCE

## compile the java
javac $JAVA_SOURCE 

## run the class using all passed in parameters from the command line
java -classpath $TEMP_DIRECTORY $CLASS_NAME

RelProxy is a Java compiler on the fly (in memory), it makes Java feel like a scripting language but with no limitation. It also supports hot class reload of Groovy classes when Groovy is used in a Java environment.

Java 11 has support for running source code without compilation.

For a file HelloWorld.java containing

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World!!!");
  }
}

you can run

java HelloWorld.java

to execute the code. There is a limitation: all the classes have to be defined in the same file.

If the file doesn't have .java extension, you need to include --source option.

For example for a file HelloWorld containing a source code you need to run

java --source 11 HelloWorld .

To run a java "script" directly in the shell you can use

#!/usr/bin/java --source 11

public class HelloWorld {
  public static void main (String[] args) {
    System.out.println("Hello World")
  }
}

where /usr/bin/java is a path to java binary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM