Java Bindings

From BaseX Documentation

Jump to: navigation, search

This article is part of the XQuery Portal. It demonstrates different ways to invoke Java code from XQuery, and it presents extensions to access the current query context from Java.

The Java Binding feature is an extensibility mechanism which enables developers to directly access Java variables and execute code from XQuery. Addressed Java code must either be contained in the Java classpath, or it must be located in the Repository.

Please bear in mind that the execution of Java code may cause side effects that conflict with the functional nature of XQuery, or may introduce new security risks to your project.




A Java class is identified by a namespace URI. The original URI is rewritten as follows:

  1. The URI Rewriting steps are applied to the URI.
  2. Slashes in the resulting URI are replaced with dots.
  3. The last path segment of the URI is capitalized and rewritten to CamelCase.

The normalization steps are skipped if the URI is prefixed with java::

Functions and Variables

Java functions and variables can be referenced and evaluated by the existing XQuery function syntax:

Type XQuery Java
Variable Q{java.lang.Integer}MIN_VALUE() Integer.MIN_VALUE
Function Q{java.lang.Object}hash-code($object) object.hashCode()
Function with types Q{java.lang.String}split·java.lang.String·int($string, ';', xs:int(3)) string.split(";", 3)

As XQuery and Java have different type systems, XQuery arguments are converted to equivalent Java values, and the result of a Java function is converted back to an XQuery value (see Data Types).

If a Java function is not found, XQuery values may need to be cast the target type. For example, if a Java function expects a primitive int value, you will need to convert your XQuery integers to xs:int.

Namespace Declarations

In the following example, Java’s Math class is referenced. When executed, the query returns the cosine of an angle by calling the static method cos(), and the value of π by addressing the static variable via PI():

declare namespace math = "java:java.lang.Math";
math:cos(xs:double(0)), math:PI()

With the Expanded QName notation of XQuery 3.0, the namespace can directly be embedded in the function call:


The constructor of a class can be invoked by calling the virtual function new(). Instance methods can then called by passing on the resulting Java object as first argument. In the following example, 256 bytes are written to the file output.txt. First, a new FileWriter instance is created, and its write() function is called in the next step:

declare namespace fw = "";
let $file := fw:new('output.txt')
return (
  for $i in 0 to 255
  return fw:write($file, xs:int($i)),

If the result of a Java call contains invalid XML characters, it will be rejected. The validity check can be disabled by setting the CHECKSTRINGS option to false. In the example below, a file with a single 00 byte is written, and this file will then be accessed by via Java functions:

declare namespace br = '';
declare namespace fr = '';

declare option db:checkstrings 'false';

file:write-binary('00.bin', xs:hexBinary('00')),
br:new(fr:new('00.bin')) ! (br:readLine(.), br:close(.))

Note that Java code cannot be pre-compiled, and will as such be evaluated slower than optimized XQuery code.

Module Imports

An alternative solution is to access Java code by importing classes as modules. A new instance of the addressed class will be created, which can then be referenced in the query body.

In the (side-effecting) example below, the size of a Java hash set is returned. The boolean values that are returned by set:add() are swallowed:

import module namespace set = "java:java.util.HashSet";
  for $s in ("one", "two", "one")
  return set:add($s)

The execution of imported classes is more efficient than the execution of instances that are created at runtime via new(). A drawback is that no arguments can be passed on to the class constructor. As a consequence, the import fails if the addressed class has no default constructor, but at least one constructor with arguments.


Java classes can be coupled even more closely to the BaseX core library. If a class inherits the abstract QueryModule class, the two variables queryContext and staticContext get available, which provide access to the global and static context of a query.

The QueryResource interface can be implemented to enforce finalizing operations, such as the closing of opened connections or resources in a module. Its close() method will be called after the XQuery expression has been fully evaluated.


The internal properties of functions can be assigned via annotations:

In the following code, information from the static query context is returned by the first function, and a query exception is raised by the second function:

import module namespace context = 'org.basex.examples.query.ContextModule';

element user {
try {
  element to-int { context:to-int('abc') }
} catch basex:error {
  element error { $err:description }

The imported Java class is shown below:

package org.basex.examples.query;

import org.basex.query.*;
import org.basex.query.value.item.*;
import org.basex.util.*;

 * This example inherits the {@link QueryModule} class and
 * implements the QueryResource interface.
public class ContextModule extends QueryModule implements QueryResource {
   * Returns the name of the logged in user.
   * @return user string
  public String user() {

   * Converts the specified string to an integer.
   * @param value string to be converted
   * @return resulting integer
   * @throws QueryException query exception
  public int toInt(final String value) throws QueryException {
    try {
      return Integer.parseInt(value);
    } catch(NumberFormatException ex) {
      throw new QueryException("Integer conversion failed: " + value);

  public void close() {
    // defined in QueryResource interface, will be called after query evaluation

The result will look as follows:

<error>Integer conversion failed: abc</error>

Please visit the XQuery 3.0 specification if you want to get more insight into function properties.


By default, a Java function will be executed in parallel with other code. However, if a Java function performs sensitive write operations, it is advisable to explicitly lock the code. This can be realized via locking annotations:

  @Lock(write = { "HEAVYIO" })
  public void write() {
    // ...

  @Lock(read = { "HEAVYIO" })
  public void read() {
    // ...

If an XQuery expression is run which calls the Java write() function, every other query that calls write() or read() needs to wait for the query to be finished. If a query calls the read() function, only those queries are queued that call write(), because this function is only annotated with a read lock. More details on parallel query execution can be found in the article on Transaction Management.

Data Types

XQuery and Java types are mapped as follows:

XQuery Type Java Type
xs:string String, char, Character
xs:boolean boolean, Boolean
xs:byte byte, Byte
xs:short short, Short
xs:int int, Integer
xs:long long, Long
xs:float float, Float
xs:double double, Double
xs:decimal java.math.BigDecimal
xs:integer java.math.BigInteger
xs:QName javax.xml.namespace.QName
empty sequence null

URI Rewriting

Before a Java class or module is accessed, its namespace URI will be normalized:

  1. If the URI is a URL:
    1. colons will be replaced with slashes,
    2. in the URI authority, the order of all substrings separated by dots is reversed, and
    3. dots in the authority and the path are replaced by slashes. If no path exists, a single slash is appended.
  2. Otherwise, if the URI is a URN, colons will be replaced with slashes.
  3. Characters other than letters, dots and slashes will be replaced with dashes.
  4. If the resulting string ends with a slash, the index string is appended.

If the resulting path has no file suffix, it may point to either an XQuery module or a Java archive:


Version 8.4
Version 8.2
Version 8.0
Version 7.8
Version 7.2.1
Personal tools