As explained in 'Customizing the Interpreter's Implementation' and 'Customizing the Behavior of Java API Access', the way of executing scripts can be customized by setting attributes of a Context object. It can be basically achieved by creating a Context object, and then calling setImplementation() method or setConfiguration() method succeedingly. However, this procedure may be lengthly and not flexible enough in some cases. Pnuts API provides a couple of more convenient ways to set up contexts.
If the predefined system properties are defined when the Pnuts classes are first loaded, they are used to set up Context objects as the default settings. For example, pnuts.lang.defaultPnutsImpl property defines the class name of the default Implementation object.
% java -Dpnuts.lang.defaultPnutsImpl=pnuts.compiler.CompilerPnutsImpl MainClass
If Pnuts.setDefault() method is called before Context class is loaded, the specified Properties override the system properties.
- public static void setDefaults( Properties properties );
import pnuts.lang.*;
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args){
try {
Properties p = new Properties();
p.load(Test.class.getResourceAsStream("test.properites"))
Pnuts.setDefaults(p);
Context context = new Context();
...
} catch (IOException e){
...
}
}
}
This method allows to change the Context settings with a property file, without code modification.
Note that the default settings can not be changed once Pnuts API (especially Context class) are loaded.
The constructor Context(Context) creates a Context object that inherits the settings of the specified Context.
import pnuts.lang.*;
public class Test {
static Context defaultContext;
static {
defaultContext = new Context();
defaultContext.usePackage("hibernate");
}
public Object execute(String script){
Context context = new Context(defaultContext);
try {
return Pnuts.load(script, context);
} catch (Exception e){
e.printStackTrace();
}
}
}