Class ScriptEvaluator
- All Implemented Interfaces:
ICookable, IMultiCookable, IScriptEvaluator
IScriptEvaluator that utilizes the JANINO Java compiler.
This implementation implements the concept of "Local methods", i.e. statements may be freely intermixed with
method declarations. These methods are typically called by the "main code" of the script evaluator. One limitation
exists: When cooking multiple scripts in one ScriptEvaluator, then local method signatures
(names and parameter types) must not collide between scripts.
A plethora of "convenience constructors" exist that execute the setup steps instantly. Their use is discouraged,
in favor of using the default constructor, plus calling a number of setters, and then one of the cook()
methods.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) classRepresents one script that thisScriptEvaluatordeclares. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final ClassBodyEvaluatorprivate Class<?> private Method[]private ScriptEvaluator.Script[]The scripts to compile.private intprivate WarningHandlerFields inherited from interface IScriptEvaluator
DEFAULT_METHOD_NAME, DEFAULT_RETURN_TYPE -
Constructor Summary
ConstructorsConstructorDescriptionConstructs a script evaluator with all the default settings.ScriptEvaluator(int count) Constructs a script evaluator with the given number of scripts.ScriptEvaluator(String script) Equivalent toScriptEvaluator(String fileName, InputStream is, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, ClassLoader parentClassLoader) Equivalent toScriptEvaluator(String fileName, Reader reader, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, ClassLoader parentClassLoader) Equivalent toScriptEvaluator(String script, Class<?> returnType) Equivalent toScriptEvaluator(String script, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes) Equivalent toScriptEvaluator(String script, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions) Equivalent toScriptEvaluator(Scanner scanner, Class<?> extendedType, Class<?>[] implementedTypes, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, ClassLoader parentClassLoader) Equivalent toScriptEvaluator(Scanner scanner, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, ClassLoader parentClassLoader) Equivalent toScriptEvaluator(Scanner scanner, String className, Class<?> extendedType, Class<?>[] implementedTypes, boolean staticMethod, Class<?> returnType, String methodName, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, ClassLoader parentClassLoader) Equivalent to -
Method Summary
Modifier and TypeMethodDescriptionprivate static <T> T[]protected Java.Type[]classesToTypes(Location location, Class<?>[] classes) protected Java.TypeclassToType(Location loc, Class<?> clazz) final voidOn a 2 GHz Intel Pentium Core Duo under Windows XP with an IBM 1.4.2 JDK, compiling 10000 expressions "a + b" (integer) takes about 4 seconds and 56 MB of main memory.voidReads, scans, parses and compiles Java tokens from the givenReader.(package private) voidcook(String fileName, Java.AbstractCompilationUnit.ImportDeclaration[] importDeclarations, Java.BlockStatement[][] statementss, Java.MethodDeclarator[][] localMethodss) protected voidcook(Java.CompilationUnit compilationUnit) Compiles the given compilationUnit, defines it into aClassLoader, loads the generated class, gets the script methods from that class, and makes them available throughgetMethod(int).final voidcook(Java.CompilationUnit compilationUnit, Collection<Java.MethodDeclarator> methodDeclarators) final voidfinal voidCooks a set of scripts into one class.private void<T> TcreateFastEvaluator(Reader reader, Class<T> interfaceToImplement, 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(String script, Class<T> interfaceToImplement, String[] parameterNames) <T> TcreateFastEvaluator(Scanner scanner, Class<?> interfaceToImplement, String[] parameterNames) Notice: This method is not declared inIScriptEvaluator, and is hence only available in this implementation oforg.codehaus.commons.compiler.static ObjectcreateFastScriptEvaluator(String script, Class<?> interfaceToImplement, String[] parameterNames) Deprecated.static ObjectcreateFastScriptEvaluator(Scanner scanner, Class<?> interfaceToImplement, String[] parameterNames, ClassLoader parentClassLoader) Deprecated.UsecreateFastEvaluator(Scanner, Class, String[])insteadstatic ObjectcreateFastScriptEvaluator(Scanner scanner, String[] defaultImports, String className, Class<?> extendedClass, Class<?> interfaceToImplement, String[] parameterNames, ClassLoader parentClassLoader) Deprecated.UsecreateFastEvaluator(Scanner,Class,String[])instead:static ObjectcreateFastScriptEvaluator(Scanner scanner, String className, Class<?> extendedType, Class<?> interfaceToImplement, String[] parameterNames, ClassLoader parentClassLoader) Deprecated.UsecreateFastEvaluator(Scanner, Class, String[])insteadevaluate()Shorthand forevaluate(new Object[0]).Same asIScriptEvaluator.evaluate(Object[]), but for multiple scripts.Calls the script with concrete parameter values.Class<?> getClazz()String[]Class<?> getMethod(int idx) Same asIScriptEvaluator.getMethod(), but for multiple scripts.(package private) Method[]Method[]protected final Class<?> getReturnType(int index) private ScriptEvaluator.ScriptgetScript(int index) static String[]guessParameterNames(Scanner scanner) Guesses the names of the parameters used in the given expression.private static String[]guessParameterNames2(Scanner scanner) private Java.MethodDeclaratormakeMethodDeclaration(Location location, Java.Annotation[] annotations, boolean staticMethod, Class<?> returnType, String methodName, Class<?>[] parameterTypes, String[] parameterNames, Class<?>[] thrownExceptions, Java.BlockStatement[] statements) protected voidmakeStatements(int idx, Parser parser, List<Java.BlockStatement> resultStatements, List<Java.MethodDeclarator> resultMethods) Parses statements from the parser until end-of-input.private static Objectprotected Java.TypeoptionalClassToType(Location loc, Class<?> clazz) options()options(EnumSet<JaninoOption> options) Sets the options for all future compilations.(package private) Java.AbstractCompilationUnit.ImportDeclaration[]parseImports(Parser parser) private static voidparseScriptStatement(Parser parser, List<Java.BlockStatement> mainStatements, List<Java.MethodDeclarator> localMethods) ScriptStatement := Statement (1) | 'class' ...voidsetClassName(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(String... defaultImports) voidsetDefaultReturnType(Class<?> defaultReturnType) When thisIScriptEvaluatoris coooked, then the defaultReturnType applies to all scripts for which no explicit return type was configured.voidsetExtendedClass(Class<?> extendedType) voidsetImplementedInterfaces(Class<?>[] implementedTypes) voidsetMethodName(String methodName) Defines the name of the generated method.voidsetMethodNames(String[] methodNames) Same asIScriptEvaluator.setMethodName(String), but for multiple scripts.voidsetOverrideMethod(boolean overrideMethod) Defines whether the generated method overrides a methods declared in a supertype.voidsetOverrideMethod(boolean[] overrideMethod) Same asIScriptEvaluator.setOverrideMethod(boolean), but for multiple scripts.voidsetParameters(String[][] parameterNames, Class<?>[][] parameterTypes) Same asIScriptEvaluator.setParameters(String[], Class[]), but for multiple scripts.voidsetParameters(String[] parameterNames, Class<?>[] parameterTypes) Defines the names and types of the parameters of the generated method.voidsetParentClassLoader(ClassLoader parentClassLoader) The "parent class loader" is used to load referenced classes.voidsetReturnType(Class<?> returnType) Defines the return type of the generated method.voidsetReturnTypes(Class<?>[] returnTypes) Configures the return types of the generated methods.voidsetScriptCount(int count) voidsetSourceVersion(int version) Specifies the version of source code accepted, in analogy with JAVAC's-sourcecommand line option.voidsetStaticMethod(boolean staticMethod) Defines whether the generated method should be STATIC or not.voidsetStaticMethod(boolean[] staticMethod) Same asIScriptEvaluator.setStaticMethod(boolean), but for multiple scripts.voidsetTargetVersion(int version) Generates class files that target a specified release of the virtual machine, in analogy with JAVAC's-targetcommand line option.voidsetThrownExceptions(Class<?>[] thrownExceptions) Defines the exceptions that the generated method may throw.voidsetThrownExceptions(Class<?>[][] thrownExceptions) Same asIScriptEvaluator.setThrownExceptions(Class[]), but for multiple scripts.voidsetWarningHandler(WarningHandler warningHandler) By default, warnings are discarded, but an application my install a customWarningHandler.Methods inherited from class MultiCookable
cook, cook, cook, cook, cook, cook, cook, cookFiles, cookFiles, cookFiles, cookFilesMethods inherited from class Cookable
cook, cook, cook, cook, cook, cook, cook, cookFile, cookFile, cookFile, cookFileMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface ICookable
cook, cook, cook, cook, cook, cook, cook, cookFile, cookFile, cookFile, cookFileMethods inherited from interface IMultiCookable
cook, cook, cook, cook, cookFiles, cookFiles, cookFiles, cookFilesMethods inherited from interface IScriptEvaluator
cook, cook, cook
-
Field Details
-
sourceVersion
private int sourceVersion -
warningHandler
-
cbe
-
scripts
The scripts to compile. Is initialized on the first call tosetStaticMethod(boolean[])or one of its friends. -
defaultReturnType
-
getMethodsCache
-
-
Constructor Details
-
ScriptEvaluator
Equivalent toScriptEvaluator se = new ScriptEvaluator(); se.cook(script);- Throws:
CompileException- See Also:
-
ScriptEvaluator
Equivalent toScriptEvaluator se = new ScriptEvaluator(); se.setReturnType(returnType); se.cook(script);- Throws:
CompileException- See Also:
-
ScriptEvaluator
public ScriptEvaluator(String script, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes) throws CompileException Equivalent toScriptEvaluator se = new ScriptEvaluator(); se.setReturnType(returnType); se.setParameters(parameterNames, parameterTypes); se.cook(script);- Throws:
CompileException- See Also:
-
ScriptEvaluator
public ScriptEvaluator(String script, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions) throws CompileException Equivalent toScriptEvaluator se = new ScriptEvaluator(); se.setReturnType(returnType); se.setParameters(parameterNames, parameterTypes); se.setThrownExceptions(thrownExceptions); se.cook(script);- Throws:
CompileException- See Also:
-
ScriptEvaluator
public ScriptEvaluator(@Nullable String fileName, InputStream is, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, @Nullable ClassLoader parentClassLoader) throws CompileException, IOException Equivalent toScriptEvaluator se = new ScriptEvaluator(); se.setReturnType(returnType); se.setParameters(parameterNames, parameterTypes); se.setThrownExceptions(thrownExceptions); se.setParentClassLoader(parentClassLoader); se.cook(fileName, is);- Throws:
CompileExceptionIOException- See Also:
-
ScriptEvaluator
public ScriptEvaluator(@Nullable String fileName, Reader reader, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, @Nullable ClassLoader parentClassLoader) throws CompileException, IOException Equivalent toScriptEvaluator se = new ScriptEvaluator(); se.setReturnType(returnType); se.setParameters(parameterNames, parameterTypes); se.setThrownExceptions(thrownExceptions); se.setParentClassLoader(parentClassLoader); se.cook(reader);- Throws:
CompileExceptionIOException- See Also:
-
ScriptEvaluator
public ScriptEvaluator(Scanner scanner, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, @Nullable ClassLoader parentClassLoader) throws CompileException, IOException Equivalent toScriptEvaluator se = new ScriptEvaluator(); se.setReturnType(returnType); se.setParameters(parameterNames, parameterTypes); se.setThrownExceptions(thrownExceptions); se.setParentClassLoader(parentClassLoader); se.cook(scanner);- Throws:
CompileExceptionIOException- See Also:
-
ScriptEvaluator
public ScriptEvaluator(Scanner scanner, @Nullable Class<?> extendedType, Class<?>[] implementedTypes, Class<?> returnType, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, @Nullable ClassLoader parentClassLoader) throws CompileException, IOException Equivalent toScriptEvaluator se = new ScriptEvaluator(); se.setExtendedType(extendedType); se.setImplementedTypes(implementedTypes); se.setReturnType(returnType); se.setParameters(parameterNames, parameterTypes); se.setThrownExceptions(thrownExceptions); se.setParentClassLoader(parentClassLoader); se.cook(scanner);- Throws:
CompileExceptionIOException- See Also:
-
ScriptEvaluator
public ScriptEvaluator(Scanner scanner, String className, @Nullable Class<?> extendedType, Class<?>[] implementedTypes, boolean staticMethod, Class<?> returnType, String methodName, String[] parameterNames, Class<?>[] parameterTypes, Class<?>[] thrownExceptions, @Nullable ClassLoader parentClassLoader) throws CompileException, IOException Equivalent toScriptEvaluator se = new ScriptEvaluator(); se.setClassName(className); se.setExtendedType(extendedType); se.setImplementedTypes(implementedTypes); se.setStaticMethod(staticMethod); se.setReturnType(returnType); se.setMethodName(methodName); se.setParameters(parameterNames, parameterTypes); se.setThrownExceptions(thrownExceptions); se.setParentClassLoader(parentClassLoader); se.cook(scanner);- Throws:
CompileExceptionIOException- See Also:
-
ScriptEvaluator
public ScriptEvaluator()Constructs a script evaluator with all the default settings. -
ScriptEvaluator
public ScriptEvaluator(int count) Constructs a script evaluator with the given number of scripts.The argument of all following invocations of
setMethodNames(String[]),setOverrideMethod(boolean[]),setParameters(String[][], Class[][]),setReturnTypes(Class[]),setStaticMethod(boolean[]),setThrownExceptions(Class[][]),cook(Parser[]),MultiCookable.cook(Reader[]),cook(Scanner[]),MultiCookable.cook(String[]),cook(String[], Reader[])andMultiCookable.cook(String[], String[])must be arrays with exactly that length.If a different constructor is used, then the first invocation of one of the above method implicitly sets the script count.
-
-
Method Details
-
setParentClassLoader
Description copied from interface:IScriptEvaluatorThe "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.
- Specified by:
setParentClassLoaderin interfaceIScriptEvaluator
-
setDebuggingInformation
public void setDebuggingInformation(boolean debugSource, boolean debugLines, boolean debugVars) Description copied from interface:IScriptEvaluatorDetermines what kind of debugging information is included in the generates classes. The default is typically "-g:none".- Specified by:
setDebuggingInformationin interfaceIScriptEvaluator
-
setSourceVersion
public void setSourceVersion(int version) Description copied from interface:ICookableSpecifies the version of source code accepted, in analogy with JAVAC's-sourcecommand line option. May be ignored by an implementation (e.g. thejaninoimplementation always accepts the language features as described on the home page). Allowed values, and the default value, depend on the implementation.-1means to use a default version.- Specified by:
setSourceVersionin interfaceICookable
-
setTargetVersion
public void setTargetVersion(int version) Description copied from interface:ICookableGenerates class files that target a specified release of the virtual machine, in analogy with JAVAC's-targetcommand line option. Allowed values depend on the implementation. The default value also depends on the implementation. The only invariant is that the generated class files are suitable for the currently executing JVM.-1means to use a default version.- Specified by:
setTargetVersionin interfaceICookable
-
setCompileErrorHandler
Description copied from interface:IScriptEvaluatorInstalls 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.- Specified by:
setCompileErrorHandlerin interfaceIScriptEvaluator- Parameters:
compileErrorHandler-nullto restore the default behavior (throwing aCompileException)
-
setWarningHandler
Description copied from interface:IScriptEvaluatorBy default, warnings are discarded, but an application my install a customWarningHandler.- Specified by:
setWarningHandlerin interfaceIScriptEvaluator- Parameters:
warningHandler-nullto indicate that no warnings be issued
-
options
- Returns:
- A reference to the currently effective compilation options; changes to it take effect immediately
-
options
Sets the options for all future compilations. -
setScriptCount
public void setScriptCount(int count) - Throws:
IllegalArgumentException- count is different from previous invocations of this method
-
getScript
-
setClassName
- Specified by:
setClassNamein interfaceIScriptEvaluator- See Also:
-
setImplementedInterfaces
- Specified by:
setImplementedInterfacesin interfaceIScriptEvaluator- See Also:
-
setExtendedClass
- Specified by:
setExtendedClassin interfaceIScriptEvaluator- See Also:
-
setDefaultReturnType
Description copied from interface:IScriptEvaluatorWhen 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.- Specified by:
setDefaultReturnTypein interfaceIScriptEvaluator- See Also:
-
getDefaultReturnType
- Specified by:
getDefaultReturnTypein interfaceIScriptEvaluator- Returns:
- The default return type that was previously configured with
IScriptEvaluator.setDefaultReturnType(Class), orIScriptEvaluator.DEFAULT_RETURN_TYPE
-
setOverrideMethod
public void setOverrideMethod(boolean overrideMethod) Description copied from interface:IScriptEvaluatorDefines whether the generated method overrides a methods declared in a supertype.- Specified by:
setOverrideMethodin interfaceIScriptEvaluator
-
setStaticMethod
public void setStaticMethod(boolean staticMethod) Description copied from interface:IScriptEvaluatorDefines whether the generated method should be STATIC or not. Defaults totrue.- Specified by:
setStaticMethodin interfaceIScriptEvaluator
-
setReturnType
Description copied from interface:IScriptEvaluatorDefines the return type of the generated method. Valuenullmeans "use the default return type".- Specified by:
setReturnTypein interfaceIScriptEvaluator- See Also:
-
setMethodName
Description copied from interface:IScriptEvaluatorDefines the name of the generated method. Initially, the method name is "eval*".- Specified by:
setMethodNamein interfaceIScriptEvaluator- Parameters:
methodName-nullmeans reset to default name- See Also:
-
setParameters
Description copied from interface:IScriptEvaluatorDefines 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.
- Specified by:
setParametersin interfaceIScriptEvaluator
-
setThrownExceptions
Description copied from interface:IScriptEvaluatorDefines the exceptions that the generated method may throw.- Specified by:
setThrownExceptionsin interfaceIScriptEvaluator
-
setOverrideMethod
public void setOverrideMethod(boolean[] overrideMethod) Description copied from interface:IScriptEvaluatorSame asIScriptEvaluator.setOverrideMethod(boolean), but for multiple scripts.- Specified by:
setOverrideMethodin interfaceIScriptEvaluator
-
setStaticMethod
public void setStaticMethod(boolean[] staticMethod) Description copied from interface:IScriptEvaluatorSame asIScriptEvaluator.setStaticMethod(boolean), but for multiple scripts.- Specified by:
setStaticMethodin interfaceIScriptEvaluator
-
setReturnTypes
Description copied from interface:IScriptEvaluatorConfigures the return types of the generated methods. If an element of the array isnull, then use the "default return type" for that script.- Specified by:
setReturnTypesin interfaceIScriptEvaluator- Parameters:
returnTypes- The methods' return types;nullelements mean "use the default return type"- See Also:
-
setMethodNames
Description copied from interface:IScriptEvaluatorSame asIScriptEvaluator.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
IScriptEvaluator.setParameters(String[][], Class[][])).- Specified by:
setMethodNamesin interfaceIScriptEvaluator
-
setParameters
Description copied from interface:IScriptEvaluatorSame asIScriptEvaluator.setParameters(String[], Class[]), but for multiple scripts.- Specified by:
setParametersin interfaceIScriptEvaluator
-
setThrownExceptions
Description copied from interface:IScriptEvaluatorSame asIScriptEvaluator.setThrownExceptions(Class[]), but for multiple scripts.- Specified by:
setThrownExceptionsin interfaceIScriptEvaluator
-
cook
Description copied from interface:ICookableReads, scans, parses and compiles Java tokens from the givenReader.- Specified by:
cookin interfaceICookable- Specified by:
cookin classCookable- Parameters:
fileName- Used when reporting errors and warnings- Throws:
CompileExceptionIOException
-
cook
On a 2 GHz Intel Pentium Core Duo under Windows XP with an IBM 1.4.2 JDK, compiling 10000 expressions "a + b" (integer) takes about 4 seconds and 56 MB of main memory. The generated class file is 639203 bytes large.The number and the complexity of the scripts is restricted by the Limitations of the Java Virtual Machine, where the most limiting factor is the 64K entries limit of the constant pool. Since every method with a distinct name requires one entry there, you can define at best 32K (very simple) scripts.
- Specified by:
cookin interfaceIMultiCookable- Specified by:
cookin interfaceIScriptEvaluator- Specified by:
cookin classMultiCookable- Throws:
CompileExceptionIOException
-
cook
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 fileName argument ofScanner(String, Reader)to distinguish between the individual token sources.On a 2 GHz Intel Pentium Core Duo under Windows XP with an IBM 1.4.2 JDK, compiling 10000 expressions "a + b" (integer) takes about 4 seconds and 56 MB of main memory. The generated class file is 639203 bytes large.
The number and the complexity of the scripts is restricted by the Limitations of the Java Virtual Machine, where the most limiting factor is the 64K entries limit of the constant pool. Since every method with a distinct name requires one entry there, you can define at best 32K (very simple) scripts.
If and only if the number of scanners is one, then that single script may contain leading IMPORT directives.
- Throws:
IllegalStateException- Any of the precedingset...()had an array size different from that ofscannersCompileExceptionIOException
-
cook
- Throws:
CompileExceptionIOException- See Also:
-
cook2
- Throws:
CompileExceptionIOException
-
cook
void cook(@Nullable String fileName, Java.AbstractCompilationUnit.ImportDeclaration[] importDeclarations, Java.BlockStatement[][] statementss, Java.MethodDeclarator[][] localMethodss) throws CompileException - Throws:
CompileException
-
cook
public final void cook(Java.CompilationUnit compilationUnit, Collection<Java.MethodDeclarator> methodDeclarators) throws CompileException - Throws:
CompileException
-
parseImports
Java.AbstractCompilationUnit.ImportDeclaration[] parseImports(@Nullable Parser parser) throws CompileException, IOException - Throws:
CompileExceptionIOException
-
getResult
- Specified by:
getResultin interfaceIScriptEvaluator- Returns:
- The generated and loaded methods that implement the cooked scripts
-
getMethods
Method[] getMethods()- Returns:
- The generated methods
- Throws:
IllegalStateException- TheScriptEvaluatorhas not yet be cooked
-
optionalClassToType
-
classToType
-
classesToTypes
-
cook
Compiles the given compilationUnit, defines it into aClassLoader, loads the generated class, gets the script methods from that class, and makes them available throughgetMethod(int).- Throws:
CompileException
-
methodKey
-
cat
- Returns:
- A copy of the followingElements, prepended with the firstElement
-
evaluate
Description copied from interface:IScriptEvaluatorShorthand forevaluate(new Object[0]).- Specified by:
evaluatein interfaceIScriptEvaluator- Throws:
InvocationTargetException
-
evaluate
Description copied from interface:IScriptEvaluatorCalls the script with concrete parameter values.Each argument must have the same type as specified through the
parameterTypesparameter ofIScriptEvaluator.setParameters(String[], Class[]).Arguments of primitive type must passed with their wrapper class objects.
The object returned has the class as specified through
IScriptEvaluator.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 withIScriptEvaluator.evaluate(int, Object[]). Thus, with version 3.1.10, the parameter was changed back toObject[].- Specified by:
evaluatein interfaceIScriptEvaluator- Parameters:
arguments- The actual parameter values- Throws:
InvocationTargetException
-
evaluate
@Nullable public Object evaluate(int idx, @Nullable Object[] arguments) throws InvocationTargetException Description copied from interface:IScriptEvaluatorSame asIScriptEvaluator.evaluate(Object[]), but for multiple scripts.- Specified by:
evaluatein interfaceIScriptEvaluator- Throws:
InvocationTargetException
-
getMethod
- Specified by:
getMethodin interfaceIScriptEvaluator- Returns:
- The generated and loaded
Method
-
getMethod
Description copied from interface:IScriptEvaluatorSame asIScriptEvaluator.getMethod(), but for multiple scripts.- Specified by:
getMethodin interfaceIScriptEvaluator
-
getClazz
- Specified by:
getClazzin interfaceIScriptEvaluator- See Also:
-
getBytecodes
- Specified by:
getBytecodesin interfaceICookable- Returns:
- The generated Java bytecode; maps class name to bytes
-
getReturnType
- Returns:
- The return type of the indexed script;
nullmeans "use thedefault return type"
-
makeStatements
protected void makeStatements(int idx, Parser parser, List<Java.BlockStatement> resultStatements, List<Java.MethodDeclarator> resultMethods) throws CompileException, IOException Parses statements from the parser until end-of-input.- Parameters:
resultStatements- Is filled with the generated statementsresultMethods- Is filled with any local methods that the script declares- Throws:
CompileExceptionIOException
-
parseScriptStatement
private static void parseScriptStatement(Parser parser, List<Java.BlockStatement> mainStatements, List<Java.MethodDeclarator> localMethods) throws CompileException, IOException ScriptStatement := Statement (1) | 'class' ... (2) | [ Modifiers ] 'void' Identifier MethodDeclarationRest (3a) | Modifiers Type Identifier MethodDeclarationRest ';' (3b) | Expression Identifier MethodDeclarationRest (3c) (5) | Modifiers Type VariableDeclarators ';' (4a) | Expression VariableDeclarators ';' (4b) (5) | Expression ';'(1): Includes the "labeled statement".
(2): Local class declaration.
(3a), (3b), (3c): Local method declaration statement.
(4) Local variable declaration statement.
(5) "Expression" must pose a type.
- Parameters:
localMethods- Filled with the methods that the script declares- Throws:
CompileExceptionIOException
-
makeMethodDeclaration
private Java.MethodDeclarator makeMethodDeclaration(Location location, Java.Annotation[] annotations, boolean staticMethod, Class<?> returnType, String methodName, Class<?>[] parameterTypes, String[] parameterNames, Class<?>[] thrownExceptions, Java.BlockStatement[] statements) -
createFastScriptEvaluator
@Deprecated public static Object createFastScriptEvaluator(String script, Class<?> interfaceToImplement, String[] parameterNames) throws CompileException Deprecated.UsecreateFastEvaluator(Scanner, Class, String[])instead- Throws:
CompileException
-
createFastScriptEvaluator
@Deprecated public static Object createFastScriptEvaluator(Scanner scanner, Class<?> interfaceToImplement, String[] parameterNames, @Nullable ClassLoader parentClassLoader) throws CompileException, IOException Deprecated.UsecreateFastEvaluator(Scanner, Class, String[])instead- Throws:
CompileExceptionIOException
-
createFastScriptEvaluator
@Deprecated public static Object createFastScriptEvaluator(Scanner scanner, String className, @Nullable Class<?> extendedType, Class<?> interfaceToImplement, String[] parameterNames, @Nullable ClassLoader parentClassLoader) throws CompileException, IOException Deprecated.UsecreateFastEvaluator(Scanner, Class, String[])instead- Throws:
CompileExceptionIOException
-
createFastScriptEvaluator
@Deprecated public static Object createFastScriptEvaluator(Scanner scanner, String[] defaultImports, String className, @Nullable Class<?> extendedClass, Class<?> interfaceToImplement, String[] parameterNames, @Nullable ClassLoader parentClassLoader) throws CompileException, IOException Deprecated.UsecreateFastEvaluator(Scanner,Class,String[])instead:ScriptEvaluatorse = newScriptEvaluator(); se.setDefaultImports.(defaultImports); se.setClassName.(className); se.setExtendedClass.(extendedClass); se.setParentClassLoader(parentClassLoader); return se.createFastEvaluator(scanner, interfaceToImplement, parameterNames);- Throws:
CompileExceptionIOException
-
setDefaultImports
- Specified by:
setDefaultImportsin interfaceIScriptEvaluator- See Also:
-
getDefaultImports
- Specified by:
getDefaultImportsin interfaceIScriptEvaluator- See Also:
-
createFastEvaluator
public <T> T createFastEvaluator(Reader reader, Class<T> interfaceToImplement, String[] parameterNames) throws CompileException, IOException Description copied from interface:IScriptEvaluatorIf 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
IScriptEvaluator.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 (seeIScriptEvaluator.setClassName(String)).- Specified by:
createFastEvaluatorin interfaceIScriptEvaluator- 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:
CompileExceptionIOException
-
createFastEvaluator
public <T> T createFastEvaluator(String script, Class<T> interfaceToImplement, String[] parameterNames) throws CompileException - Specified by:
createFastEvaluatorin interfaceIScriptEvaluator- Parameters:
script- Contains the sequence of script tokens- Throws:
CompileException- See Also:
-
createFastEvaluator
public <T> T createFastEvaluator(Scanner scanner, Class<?> interfaceToImplement, String[] parameterNames) throws CompileException, IOException Notice: This method is not declared inIScriptEvaluator, and is hence only available in this implementation oforg.codehaus.commons.compiler. To be independent from this particular implementation, try to switch tocreateFastEvaluator(Reader, Class, String[]).- Parameters:
scanner- Source of tokens to read- Throws:
CompileExceptionIOException- See Also:
-
guessParameterNames
Guesses the names of the parameters used in the given expression. The strategy is to look at all "ambiguous names" in the expression (e.g. in "a.b.c.d()", the ambiguous name is "a.b.c"), and then at the components of the ambiguous name.- If any component starts with an upper-case letter, then ambiguous name is assumed to be a type name.
- Otherwise, if the first component of the ambiguous name matches the name of a previously defined local variable, then the first component of the ambiguous name is assumed to be a local variable name. (Notice that this strategy does not consider that the scope of a local variable declaration may end before the end of the script.)
- Otherwise, the first component of the ambiguous name is assumed to be a parameter name.
- Throws:
CompileExceptionIOException- See Also:
-
guessParameterNames2
- Throws:
CompileExceptionIOException
-
createFastEvaluator(Scanner, Class, String[])instead