Top Description Fields Methods
org.codehaus.commons.compiler

public Interface IScriptEvaluator

extends ICookable, IMultiCookable
Imports
java.io.IOException, .Reader, java.lang.reflect.InvocationTargetException, .Method, org.codehaus.commons.compiler.lang.ClassLoaders, org.codehaus.commons.nullanalysis.Nullable

An engine that executes a script in JVM bytecode.

The syntax of the script to compile is a sequence of import declarations (not allowed if you compile many scripts at a time, see below) followed by a sequence of statements, as defined in the Java Language Specification, Java SE 7 Edition, sections 7.5 and 14.

An implementation may or may not implement the concept of "local methods", i.e. method declarations being freely intermixed with statements.

Example:

  import java.text.*;

  System.out.println("HELLO");
  System.out.println(new DecimalFormat("####,###.##").format(a));

(Notice that this expression refers to a parameter "a", as explained below.)

The script may complete abnormally, e.g. through a RETURN statement:

  if (a == null) {
      System.out.println("Oops!");
      return;
  }

Optionally, the script may be declared with a non-void return type. In this case, the last statement of the script must be a RETURN statement (or a THROW statement), and all RETURN statements in the script must return a value with the given type.

The script evaluator is implemented by creating and compiling a temporary compilation unit defining one class with one method the body of which consists of the statements of the script.

To set up a IScriptEvaluator object, proceed as follows:

  1. Create an IScriptEvaluator-implementing class.
  2. Configure the IScriptEvaluator by calling any of the following methods:
  3. Call any of the org.codehaus.commons.compiler.Cookable#cook(Reader) methods to scan, parse, compile and load the script into the JVM.

After the IScriptEvaluator object is created, the script can be executed as often with different parameter values (see evaluate(Object[])). This execution is very fast, compared to the compilation.

Less common methods exist that allow for the specification of the name of the generated class, the class it extends, the interfaces it implements, the name of the method that executes the script, the exceptions that this method (i.e. the script) is allowed to throw, and the ClassLoader that is used to define the generated class and to load classes referenced by the script.

If you want to compile many scripts at the same time, you have the option to cook an array of scripts in one IScriptEvaluator by using the following methods:

Notice that these methods have array parameters in contrast to their one-script brethren.

Field Summary

Modifier and TypeField and Description
public static final String
DEFAULT_METHOD_NAME

The name of the generated method(s), if no custom method name is configured with setMethodNames(String[]).

public static final Class<?>
DEFAULT_RETURN_TYPE

The return type for any script for which no return type is explicitly configured.

Method Summary

Modifier and TypeMethod and Description
public void
cook(Reader... readers)

Redeclares org.codehaus.commons.compiler.IMultiCookable.cook.

Same as cook(Reader), but for multiple scripts.
public void
cook(String[] fileNames, Reader[] readers)

Redeclares org.codehaus.commons.compiler.IMultiCookable.cook.

Same as cook(String, Reader), but cooks a set of scripts into one class.
public void
cook(String[] strings)

Redeclares org.codehaus.commons.compiler.IMultiCookable.cook.

Same as cook(String), but for multiple scripts.
public void
cook(String[] fileNames, String[] strings)

Redeclares org.codehaus.commons.compiler.IMultiCookable.cook.

Same as cook(String, String), but for multiple scripts.
public <T> T
createFastEvaluator(String
Contains the sequence of script tokens
script
,
Class<T> interfaceToImplement, String[] parameterNames)

public <T> T

Returns:

An object that implements the given interface
createFastEvaluator
(Reader
Produces the stream of script tokens
reader
,
Class<T>
Must declare exactly one method
interfaceToImplement
,
String[]
The names of the parameters of that method
parameterNames
)

If the parameter and return types of the expression are known at compile time, then a "fast" script evaluator can be instantiated through this method.

public Object
evaluate()

Shorthand for evaluate(new Object[0]).

public Object
evaluate(Object[]
The actual parameter values
arguments
)

Calls the script with concrete parameter values.

public Object
evaluate(int idx, Object[] arguments)

Same as evaluate(Object[]), but for multiple scripts.

public Class<?>
public String[]
public Class<?>

Returns:

The default return type that was previously configured with setDefaultReturnType(Class), or DEFAULT_RETURN_TYPE
getDefaultReturnType
()

public Method

Returns:

The generated and loaded java.lang.reflect.Method
getMethod
()

public Method
getMethod(int idx)

Same as getMethod(), but for multiple scripts.

public Method[]

Returns:

The generated and loaded methods that implement the cooked scripts
getResult
()

public void
setClassName(String className)

public void
setCompileErrorHandler(ErrorHandler
null to restore the default behavior (throwing a CompileException)
compileErrorHandler
)

Installs an ErrorHandler which is invoked during compilation on each error.

public void
setDebuggingInformation(boolean debugSource, boolean debugLines, boolean debugVars)

Determines what kind of debugging information is included in the generates classes.

public void
setDefaultImports(String... defaultImports)

public void
setDefaultReturnType(Class<?> defaultReturnType)

When this IScriptEvaluator is coooked, then the defaultReturnType applies to all scripts for which no explicit return type was configured.

public void
setExtendedClass(Class<?> extendedClass)

public void
setImplementedInterfaces(Class<?>[] implementedInterfaces)

public void
setMethodName(String
null means reset to default name
methodName
)

Defines the name of the generated method.

public void
setMethodNames(String[] methodNames)

Same as setMethodName(String), but for multiple scripts.

public void
setOverrideMethod(boolean overrideMethod)

Defines whether the generated method overrides a methods declared in a supertype.

public void
setOverrideMethod(boolean[] overrideMethod)

Same as setOverrideMethod(boolean), but for multiple scripts.

public void
setParameters(String[] names, Class<?>[] types)

Defines the names and types of the parameters of the generated method.

public void
setParameters(String[][] names, Class<?>[][] types)

Same as setParameters(String[], Class[]), but for multiple scripts.

public void
setParentClassLoader(ClassLoader parentClassLoader)

The "parent class loader" is used to load referenced classes.

public void
setReturnType(Class<?> returnType)

Defines the return type of the generated method.

public void
setReturnTypes(Class<?>[]
The methods' return types; null elements mean "use the default return type"
returnTypes
)

Configures the return types of the generated methods.

public void
setStaticMethod(boolean staticMethod)

Defines whether the generated method should be STATIC or not.

public void
setStaticMethod(boolean[] staticMethod)

Same as setStaticMethod(boolean), but for multiple scripts.

public void
setThrownExceptions(Class<?>[] thrownExceptions)

Defines the exceptions that the generated method may throw.

public void
setThrownExceptions(Class<?>[][] thrownExceptions)

Same as setThrownExceptions(Class[]), but for multiple scripts.

public void
setWarningHandler(WarningHandler
null to indicate that no warnings be issued
warningHandler
)

By default, warnings are discarded, but an application my install a custom WarningHandler.

Inherited from org.codehaus.commons.compiler.ICookable:
cookcookcookcookcookcookcookcookcookFilecookFilecookFilecookFilegetBytecodessetSourceVersionsetTargetVersion
Inherited from org.codehaus.commons.compiler.IMultiCookable:
cookcookcookcookcookFilescookFilescookFilescookFiles

Field Detail

DEFAULT_METHOD_NAMEback to summary
public static final String DEFAULT_METHOD_NAME

The name of the generated method(s), if no custom method name is configured with setMethodNames(String[]).

The '*' in this string is replaced with the method index, starting at 0.

DEFAULT_RETURN_TYPEback to summary
public static final Class<?> DEFAULT_RETURN_TYPE

The return type for any script for which no return type is explicitly configured.

Method Detail

cookback to summary
public void cook(Reader... readers) throws CompileException, IOException

Redeclares org.codehaus.commons.compiler.IMultiCookable.cook.

Same as cook(Reader), but for multiple scripts.

Annotations
@Override
cookback to summary
public void cook(String[] fileNames, Reader[] readers) throws CompileException, IOException

Redeclares org.codehaus.commons.compiler.IMultiCookable.cook.

Same as cook(String, Reader), but cooks a set of scripts into one class. Notice that if any of the scripts causes trouble, the entire compilation will fail. If you need to report which of the scripts causes the exception, you may want to use the fileNames parameter to distinguish between the individual token sources.

Iff the number of scanners is one, then that single script may contain leading IMPORT directives.

s
Annotations
@Override
Exceptions
IllegalStateException:
if any of the preceding set...() had an array size different from that of scanners
cookback to summary
public void cook(String[] strings) throws CompileException

Redeclares org.codehaus.commons.compiler.IMultiCookable.cook.

Same as cook(String), but for multiple scripts.

Annotations
@Override
cookback to summary
public void cook(String[] fileNames, String[] strings) throws CompileException

Redeclares org.codehaus.commons.compiler.IMultiCookable.cook.

Same as cook(String, String), but for multiple scripts.

Annotations
@Override
createFastEvaluatorback to summary
public <T> T createFastEvaluator(String script, Class<T> interfaceToImplement, String[] parameterNames) throws CompileException
Parameters
script:String

Contains the sequence of script tokens

See Also
createFastEvaluator(Reader, Class, String[])
createFastEvaluatorback to summary
public <T> T createFastEvaluator(Reader reader, Class<T> interfaceToImplement, String[] parameterNames) throws CompileException, IOException

If the parameter and return types of the expression are known at compile time, then a "fast" script evaluator can be instantiated through this method.

Script evaluation is faster than through evaluate(Object[]), because it is not done through reflection but through direct method invocation.

Example:

public interface Foo {
    int bar(int a, int b);
}
...
IScriptEvaluator se = CompilerFactoryFactory.getDefaultCompilerFactory().newScriptEvaluator();

// Optionally configure the SE her:
se.setClassName("Bar");
se.setDefaultImports(new String[] { "java.util.*" });
se.setExtendedClass(SomeOtherClass.class);
se.setParentClassLoader(someClassLoader);

Foo f = (Foo) se.createFastScriptEvaluator(
    "return a - b;",
    Foo.class,
    new String[] { "a", "b" }
);
System.out.println("1 - 2 = " + f.bar(1, 2));

All other configuration (implemented type, static method, return type, method name, parameter names and types, thrown exceptions) are predetermined by the interfaceToImplement.

Notice: The interfaceToImplement must either be declared public, or with package scope in the same package as the generated class (see setClassName(String)).

s
Parameters
reader:Reader

Produces the stream of script tokens

interfaceToImplement:Class<T>

Must declare exactly one method

parameterNames:String[]

The names of the parameters of that method

Returns:T

An object that implements the given interface

evaluateback to summary
public Object evaluate() throws InvocationTargetException

Shorthand for evaluate(new Object[0]).

Annotations
@Nullable
evaluateback to summary
public Object evaluate(Object[] arguments) throws InvocationTargetException

Calls the script with concrete parameter values.

Each argument must have the same type as specified through the parameterTypes parameter of setParameters(String[], Class[]).

Arguments of primitive type must passed with their wrapper class objects.

The object returned has the class as specified through setReturnType(Class).

This method is thread-safe.

Notice: In version 3.1.8, the arguments parameter was changed from Object[] to Object..., which turned out to be a really bad decision because it caused a very ugly invocation ambiguity with evaluate(int, Object[]). Thus, with version 3.1.10, the parameter was changed back to Object[].

Parameters
arguments:Object[]

The actual parameter values

Annotations
@Nullable
Exceptions
IllegalStateException:
This IScriptEvaluator is not yet cooked
evaluateback to summary
public Object evaluate(int idx, Object[] arguments) throws InvocationTargetException

Same as evaluate(Object[]), but for multiple scripts.

Annotations
@Nullable
getClazzback to summary
public Class<?> getClazz()
See Also
IClassBodyEvaluator#getClazz()
getDefaultImportsback to summary
public String[] getDefaultImports()
See Also
IClassBodyEvaluator#getDefaultImports()
getDefaultReturnTypeback to summary
public Class<?> getDefaultReturnType()
Returns:Class<?>

The default return type that was previously configured with setDefaultReturnType(Class), or DEFAULT_RETURN_TYPE

getMethodback to summary
public Method getMethod()
Returns:Method

The generated and loaded java.lang.reflect.Method

Exceptions
IllegalStateException:
This IScriptEvaluator is not yet cooked
getMethodback to summary
public Method getMethod(int idx)

Same as getMethod(), but for multiple scripts.

getResultback to summary
public Method[] getResult()
Returns:Method[]

The generated and loaded methods that implement the cooked scripts

Exceptions
IllegalStateException:
This IScriptEvaluator is not yet cooked
setClassNameback to summary
public void setClassName(String className)
See Also
IClassBodyEvaluator#setClassName(String)
setCompileErrorHandlerback to summary
public void setCompileErrorHandler(ErrorHandler compileErrorHandler)

Installs an ErrorHandler which is invoked during compilation on each error. (By default, the compilation throws a CompileException on the first error and terminates.)

If the given ErrorHandler throws a CompileException, then the compilation terminates and the exception is propagated.

If the given ErrorHandler does not throw a CompileException but completes normally, then the compilation may or may not continue, depending on the error. Iff the compilation completes normally but errors were reported, then it will throw a CompileException indicating the number of errors.

In other words: The ErrorHandler may throw a CompileException or not, but the compilation will definitely throw a CompileException if one or more compile errors have occurred.

Parameters
compileErrorHandler:ErrorHandler

null to restore the default behavior (throwing a CompileException)

setDebuggingInformationback to summary
public void setDebuggingInformation(boolean debugSource, boolean debugLines, boolean debugVars)

Determines what kind of debugging information is included in the generates classes. The default is typically "-g:none".

setDefaultImportsback to summary
public void setDefaultImports(String... defaultImports)
See Also
IClassBodyEvaluator#setDefaultImports(String...)
setDefaultReturnTypeback to summary
public void setDefaultReturnType(Class<?> defaultReturnType)

When this IScriptEvaluator is coooked, then the defaultReturnType applies to all scripts for which no explicit return type was configured.

The initial default return type (if you want, the "default-default" return type) is void.class.

See Also
setReturnType(Class), setReturnTypes(Class[])
setExtendedClassback to summary
public void setExtendedClass(Class<?> extendedClass)
See Also
IClassBodyEvaluator#setExtendedClass(Class)
setImplementedInterfacesback to summary
public void setImplementedInterfaces(Class<?>[] implementedInterfaces)
See Also
IClassBodyEvaluator#setImplementedInterfaces(Class[])
setMethodNameback to summary
public void setMethodName(String methodName)

Defines the name of the generated method. Initially, the method name is eval*.

Parameters
methodName:String

null means reset to default name

See Also
IScriptEvaluator#DEFAULT_METHOD_NAME
setMethodNamesback to summary
public void setMethodNames(String[] methodNames)

Same as setMethodName(String), but for multiple scripts.

Define the names of the generated methods. By default the methods have distinct and implementation-specific names.

If two scripts have the same name, then they must have different parameter types (see setParameters(String[][], Class[][])).

setOverrideMethodback to summary
public void setOverrideMethod(boolean overrideMethod)

Defines whether the generated method overrides a methods declared in a supertype.

setOverrideMethodback to summary
public void setOverrideMethod(boolean[] overrideMethod)

Same as setOverrideMethod(boolean), but for multiple scripts.

setParametersback to summary
public void setParameters(String[] names, Class<?>[] types)

Defines the names and types of the parameters of the generated method.

names.length and types.length must be equal. This invariant may be checked immediately, or later when the script is cooked.

The parameters can be of primitive type, e.g. double.class.

The default is to have zero parameters.

setParametersback to summary
public void setParameters(String[][] names, Class<?>[][] types)

Same as setParameters(String[], Class[]), but for multiple scripts.

setParentClassLoaderback to summary
public void setParentClassLoader(ClassLoader parentClassLoader)

The "parent class loader" is used to load referenced classes. Useful values are:

System.getSystemClassLoader() The running JVM's class path
Thread.currentThread().getContextClassLoader() or null The class loader effective for the invoking thread
ClassLoaders#BOOTCLASSPATH_CLASS_LOADER The running JVM's boot class path

The parent class loader defaults to the current thread's context class loader.

setReturnTypeback to summary
public void setReturnType(Class<?> returnType)

Defines the return type of the generated method. Value null means "use the default return type".

See Also
setDefaultReturnType(Class)
setReturnTypesback to summary
public void setReturnTypes(Class<?>[] returnTypes)

Configures the return types of the generated methods. If an element of the array is null, then use the "default return type" for that script.

Parameters
returnTypes:Class<?>[]

The methods' return types; null elements mean "use the default return type"

See Also
setDefaultReturnType(Class), getDefaultReturnType()
setStaticMethodback to summary
public void setStaticMethod(boolean staticMethod)

Defines whether the generated method should be STATIC or not. Defaults to true.

setStaticMethodback to summary
public void setStaticMethod(boolean[] staticMethod)

Same as setStaticMethod(boolean), but for multiple scripts.

setThrownExceptionsback to summary
public void setThrownExceptions(Class<?>[] thrownExceptions)

Defines the exceptions that the generated method may throw.

setThrownExceptionsback to summary
public void setThrownExceptions(Class<?>[][] thrownExceptions)

Same as setThrownExceptions(Class[]), but for multiple scripts.

setWarningHandlerback to summary
public void setWarningHandler(WarningHandler warningHandler)

By default, warnings are discarded, but an application my install a custom WarningHandler.

Parameters
warningHandler:WarningHandler

null to indicate that no warnings be issued