You can use the XCompilationFactory interface and its various
compile and load methods to compile an expression, query, or stylesheet
in advance. The Java™ classes
can be loaded at execution time, therefore avoiding the cost of compilation
in the application run time.
Procedure
- Retrieve the XCompilationFactory by calling the getCompilationFactory
method on the XFactory class.
An XCompilationFactory
instance is associated with a particular XFactory instance, so they
share registered schemas. If a new schema is registered with the XFactory
instance; therefore, it is visible to the associated XCompilationFactory
instance.
- Create a new XCompilationParameters instance by calling
the XCompilationFactory newCompilationParameters method, passing in
the base class name to use for the generated classes.
Configure
the parameters further by using the set methods described in this
table.
Table 1. Valid set methods. These
set methods are defined in the XCompilationParameters interface and
are valid for generating a precompiled executable.
Set Methods Valid for Generating a Precompiled
Executable |
Description |
Default |
setPackageName |
Specify the package name for the generated classes. The
value must be a valid Java package
name.
|
Java default
package |
setDirectoryName |
Specify the directory to which the generated
classes should be written. The directory must exist.
|
Current working directory as retrieved
by calling the Java System.getProperty
method with the property user.dir |
The setClassLoader method is only valid when loading the generated
classes using one of the load methods. If the class loader is set
at compile time, it is ignored.
- Use one of the compile methods on the XCompilationFactory,
passing in the XCompilationParameters, to generate the precompiled
executable.
The compile methods use the XStaticContext
just like the XFactory prepare methods to configure prepare-time settings.
Note that compilation is implied when the compile methods are used;
therefore, changing the use-compiler setting through the XStaticContext
setUseCompiler method has no effect on these methods. If no static
context is specified, the default settings are used.
Example
The following is a basic example of precompiling an XPath
expression.
// Create the factory
XFactory factory = XFactory.newInstance();
// Get the compilation factory
XCompilationFactory compileFactory = factory.getCompilationFactory();
// Create the compilation parameters
XCompilationParameters params = compileFactory.newCompilationParameters("MyXPath");
params.setPackageName("org.example.myxpath");
// Generate the compiled classes
compileFactory.compileXPath("/doc/item[@id > 3000]", params);
Appropriate
compile methods are available for XQuery and XSLT as well.