Interface IScriptEvaluator
-
- All Superinterfaces:
ICookable,IMultiCookable
- All Known Implementing Classes:
ScriptEvaluator,ScriptEvaluator
public interface IScriptEvaluator extends ICookable, IMultiCookable
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
IScriptEvaluatorobject, proceed as follows:- Create an
IScriptEvaluator-implementing class. -
Configure the
IScriptEvaluatorby calling any of the following methods: -
Call any of the
Cookable.cook(Reader)methods to scan, parse, compile and load the script into the JVM.
After the
IScriptEvaluatorobject is created, the script can be executed as often with different parameter values (seeevaluate(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
ClassLoaderthat 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
IScriptEvaluatorby using the following methods:setMethodNames(String[])setParameters(String[][], Class[][])setReturnTypes(Class[])setStaticMethod(boolean[])setThrownExceptions(Class[][])ICookable.cook(Reader)evaluate(int, Object[])
Notice that these methods have array parameters in contrast to their one-script brethren.
-
-
Field Summary
Fields Modifier and Type Field Description static java.lang.StringDEFAULT_METHOD_NAMEThe name of the generated method(s), if no custom method name is configured withsetMethodNames(String[]).static java.lang.Class<?>DEFAULT_RETURN_TYPEThe return type for any script for which no return type is explicitly configured.
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description voidcook(java.io.Reader... readers)Same asICookable.cook(Reader), but for multiple scripts.voidcook(java.lang.String[] strings)Same asICookable.cook(String), but for multiple scripts.voidcook(java.lang.String[] fileNames, java.io.Reader[] readers)Same asICookable.cook(String, Reader), but cooks a set of scripts into one class.voidcook(java.lang.String[] fileNames, java.lang.String[] strings)Same asICookable.cook(String, String), but for multiple scripts.<T> TcreateFastEvaluator(java.io.Reader reader, java.lang.Class<T> interfaceToImplement, java.lang.String[] 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.<T> TcreateFastEvaluator(java.lang.String script, java.lang.Class<T> interfaceToImplement, java.lang.String[] parameterNames)java.lang.Objectevaluate()Shorthand forevaluate(new Object[0]).java.lang.Objectevaluate(int idx, java.lang.Object[] arguments)Same asevaluate(Object[]), but for multiple scripts.java.lang.Objectevaluate(java.lang.Object[] arguments)Calls the script with concrete parameter values.java.lang.Class<?>getClazz()java.lang.String[]getDefaultImports()java.lang.Class<?>getDefaultReturnType()java.lang.reflect.MethodgetMethod()java.lang.reflect.MethodgetMethod(int idx)Same asgetMethod(), but for multiple scripts.java.lang.reflect.Method[]getResult()voidsetClassName(java.lang.String className)voidsetCompileErrorHandler(ErrorHandler compileErrorHandler)Installs anErrorHandlerwhich is invoked during compilation on each error.voidsetDebuggingInformation(boolean debugSource, boolean debugLines, boolean debugVars)Determines what kind of debugging information is included in the generates classes.voidsetDefaultImports(java.lang.String... defaultImports)voidsetDefaultReturnType(java.lang.Class<?> defaultReturnType)When thisIScriptEvaluatoris coooked, then the defaultReturnType applies to all scripts for which no explicit return type was configured.voidsetExtendedClass(java.lang.Class<?> extendedClass)voidsetImplementedInterfaces(java.lang.Class<?>[] implementedInterfaces)voidsetMethodName(java.lang.String methodName)Defines the name of the generated method.voidsetMethodNames(java.lang.String[] methodNames)Same assetMethodName(String), but for multiple scripts.voidsetOverrideMethod(boolean overrideMethod)Defines whether the generated method overrides a methods declared in a supertype.voidsetOverrideMethod(boolean[] overrideMethod)Same assetOverrideMethod(boolean), but for multiple scripts.voidsetParameters(java.lang.String[][] names, java.lang.Class<?>[][] types)Same assetParameters(String[], Class[]), but for multiple scripts.voidsetParameters(java.lang.String[] names, java.lang.Class<?>[] types)Defines the names and types of the parameters of the generated method.voidsetParentClassLoader(java.lang.ClassLoader parentClassLoader)The "parent class loader" is used to load referenced classes.voidsetReturnType(java.lang.Class<?> returnType)Defines the return type of the generated method.voidsetReturnTypes(java.lang.Class<?>[] returnTypes)Configures the return types of the generated methods.voidsetStaticMethod(boolean staticMethod)Defines whether the generated method should be STATIC or not.voidsetStaticMethod(boolean[] staticMethod)Same assetStaticMethod(boolean), but for multiple scripts.voidsetThrownExceptions(java.lang.Class<?>[] thrownExceptions)Defines the exceptions that the generated method may throw.voidsetThrownExceptions(java.lang.Class<?>[][] thrownExceptions)Same assetThrownExceptions(Class[]), but for multiple scripts.voidsetWarningHandler(WarningHandler warningHandler)By default, warnings are discarded, but an application my install a customWarningHandler.
-
-
-
Field Detail
-
DEFAULT_METHOD_NAME
static final java.lang.String DEFAULT_METHOD_NAME
The name of the generated method(s), if no custom method name is configured withsetMethodNames(String[]).The
'*'in this string is replaced with the method index, starting at 0.- See Also:
- Constant Field Values
-
DEFAULT_RETURN_TYPE
static final java.lang.Class<?> DEFAULT_RETURN_TYPE
The return type for any script for which no return type is explicitly configured.
-
-
Method Detail
-
setParentClassLoader
void setParentClassLoader(@Nullable java.lang.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()ornullThe class loader effective for the invoking thread ClassLoaders.BOOTCLASSPATH_CLASS_LOADERThe running JVM's boot class path The parent class loader defaults to the current thread's context class loader.
-
setDebuggingInformation
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".
-
setCompileErrorHandler
void setCompileErrorHandler(@Nullable ErrorHandler compileErrorHandler)
Installs anErrorHandlerwhich is invoked during compilation on each error. (By default, the compilation throws aCompileExceptionon the first error and terminates.)If the given
ErrorHandlerthrows aCompileException, then the compilation terminates and the exception is propagated.If the given
ErrorHandlerdoes not throw aCompileExceptionbut 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 aCompileExceptionindicating the number of errors.In other words: The
ErrorHandlermay throw aCompileExceptionor not, but the compilation will definitely throw aCompileExceptionif one or more compile errors have occurred.- Parameters:
compileErrorHandler-nullto restore the default behavior (throwing aCompileException)
-
setWarningHandler
void setWarningHandler(@Nullable WarningHandler warningHandler)
By default, warnings are discarded, but an application my install a customWarningHandler.- Parameters:
warningHandler-nullto indicate that no warnings be issued
-
setClassName
void setClassName(java.lang.String className)
- See Also:
IClassBodyEvaluator.setClassName(String)
-
setImplementedInterfaces
void setImplementedInterfaces(java.lang.Class<?>[] implementedInterfaces)
-
setExtendedClass
void setExtendedClass(java.lang.Class<?> extendedClass)
-
setDefaultReturnType
void setDefaultReturnType(java.lang.Class<?> defaultReturnType)
When thisIScriptEvaluatoris 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[])
-
getDefaultReturnType
java.lang.Class<?> getDefaultReturnType()
- Returns:
- The default return type that was previously configured with
setDefaultReturnType(Class), orDEFAULT_RETURN_TYPE
-
setOverrideMethod
void setOverrideMethod(boolean overrideMethod)
Defines whether the generated method overrides a methods declared in a supertype.
-
setStaticMethod
void setStaticMethod(boolean staticMethod)
Defines whether the generated method should be STATIC or not. Defaults totrue.
-
setReturnType
void setReturnType(java.lang.Class<?> returnType)
Defines the return type of the generated method. Valuenullmeans "use the default return type".- See Also:
setDefaultReturnType(Class)
-
setMethodName
void setMethodName(@Nullable java.lang.String methodName)
Defines the name of the generated method. Initially, the method name is "eval*".- Parameters:
methodName-nullmeans reset to default name- See Also:
DEFAULT_METHOD_NAME
-
setParameters
void setParameters(java.lang.String[] names, java.lang.Class<?>[] types)Defines the names and types of the parameters of the generated method.names
.lengthand types.lengthmust 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.
-
setThrownExceptions
void setThrownExceptions(java.lang.Class<?>[] thrownExceptions)
Defines the exceptions that the generated method may throw.
-
evaluate
@Nullable java.lang.Object evaluate() throws java.lang.reflect.InvocationTargetException
Shorthand forevaluate(new Object[0]).- Throws:
java.lang.reflect.InvocationTargetException
-
evaluate
@Nullable java.lang.Object evaluate(@Nullable java.lang.Object[] arguments) throws java.lang.reflect.InvocationTargetException
Calls the script with concrete parameter values.Each argument must have the same type as specified through the
parameterTypesparameter ofsetParameters(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[]toObject..., which turned out to be a really bad decision because it caused a very ugly invocation ambiguity withevaluate(int, Object[]). Thus, with version 3.1.10, the parameter was changed back toObject[].- Parameters:
arguments- The actual parameter values- Throws:
java.lang.IllegalStateException- This IScriptEvaluator is not yet cookedjava.lang.reflect.InvocationTargetException
-
getMethod
java.lang.reflect.Method getMethod()
- Returns:
- The generated and loaded
Method - Throws:
java.lang.IllegalStateException- This IScriptEvaluator is not yet cooked
-
setOverrideMethod
void setOverrideMethod(boolean[] overrideMethod)
Same assetOverrideMethod(boolean), but for multiple scripts.
-
setStaticMethod
void setStaticMethod(boolean[] staticMethod)
Same assetStaticMethod(boolean), but for multiple scripts.
-
setReturnTypes
void setReturnTypes(java.lang.Class<?>[] returnTypes)
Configures the return types of the generated methods. If an element of the array isnull, then use the "default return type" for that script.- Parameters:
returnTypes- The methods' return types;nullelements mean "use the default return type"- See Also:
setDefaultReturnType(Class),getDefaultReturnType()
-
setMethodNames
void setMethodNames(java.lang.String[] methodNames)
Same assetMethodName(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[][])).
-
setParameters
void setParameters(java.lang.String[][] names, java.lang.Class<?>[][] types)Same assetParameters(String[], Class[]), but for multiple scripts.
-
setThrownExceptions
void setThrownExceptions(java.lang.Class<?>[][] thrownExceptions)
Same assetThrownExceptions(Class[]), but for multiple scripts.
-
cook
void cook(java.io.Reader... readers) throws CompileException, java.io.IOException
Same asICookable.cook(Reader), but for multiple scripts.- Specified by:
cookin interfaceIMultiCookable- Throws:
CompileExceptionjava.io.IOException
-
cook
void cook(java.lang.String[] fileNames, java.io.Reader[] readers) throws CompileException, java.io.IOExceptionSame asICookable.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 thefileNamesparameter to distinguish between the individual token sources.Iff the number of scanners is one, then that single script may contain leading IMPORT directives.
s- Specified by:
cookin interfaceIMultiCookable- Throws:
java.lang.IllegalStateException- if any of the precedingset...()had an array size different from that ofscannersCompileExceptionjava.io.IOException
-
cook
void cook(java.lang.String[] strings) throws CompileException
Same asICookable.cook(String), but for multiple scripts.- Specified by:
cookin interfaceIMultiCookable- Throws:
CompileException
-
cook
void cook(java.lang.String[] fileNames, java.lang.String[] strings) throws CompileExceptionSame asICookable.cook(String, String), but for multiple scripts.- Specified by:
cookin interfaceIMultiCookable- Throws:
CompileException
-
evaluate
@Nullable java.lang.Object evaluate(int idx, @Nullable java.lang.Object[] arguments) throws java.lang.reflect.InvocationTargetException
Same asevaluate(Object[]), but for multiple scripts.- Throws:
java.lang.reflect.InvocationTargetException
-
getMethod
java.lang.reflect.Method getMethod(int idx)
Same asgetMethod(), but for multiple scripts.
-
createFastEvaluator
<T> T createFastEvaluator(java.lang.String script, java.lang.Class<T> interfaceToImplement, java.lang.String[] parameterNames) throws CompileException- Parameters:
script- Contains the sequence of script tokens- Throws:
CompileException- See Also:
createFastEvaluator(Reader, Class, String[])
-
createFastEvaluator
<T> T createFastEvaluator(java.io.Reader reader, java.lang.Class<T> interfaceToImplement, java.lang.String[] parameterNames) throws CompileException, java.io.IOExceptionIf 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
sinterfaceToImplementmust either be declaredpublic, or with package scope in the same package as the generated class (seesetClassName(String)).- Parameters:
reader- Produces the stream of script tokensinterfaceToImplement- Must declare exactly one methodparameterNames- The names of the parameters of that method- Returns:
- An object that implements the given interface
- Throws:
CompileExceptionjava.io.IOException
-
setDefaultImports
void setDefaultImports(java.lang.String... defaultImports)
-
getDefaultImports
java.lang.String[] getDefaultImports()
- See Also:
IClassBodyEvaluator.getDefaultImports()
-
getClazz
java.lang.Class<?> getClazz()
- See Also:
IClassBodyEvaluator.getClazz()
-
getResult
java.lang.reflect.Method[] getResult()
- Returns:
- The generated and loaded methods that implement the cooked scripts
- Throws:
java.lang.IllegalStateException- ThisIScriptEvaluatoris not yet cooked
-
-