Writing reflexive extension functions in Java

Reflexive extension functions written in Java map the namespace of the XPath function name to a Java fully-qualified class name, and the local name of the function to a Java method or field name.

An extension function is invoked using a name such as prefix:localname(). The prefix must be the prefix associated with a namespace declaration that is in scope. The namespace URI is used to identify a Java class, and the local name is used to identify a method, field, or constructor within the class.

There are a number of extension functions supplied with the Saxon product: for details, see Extensions. The source code of these methods, which in most cases is extremely simple, can be used as an example for writing other user extension functions. It is found in class net.sf.saxon.functions.Extensions.

The command line option -TJ is useful for debugging the loading of Java extensions. It gives detailed information about the methods that are examined for a possible match.

Identifying the Java Class

There are various ways a mapping from URIs to Java classes can be established. The simplest is to use a URI that identifies the Java class explicitly. The namespace URI should be "java:" followed by the fully-qualified class name (for example xmlns:date="java:java.util.Date"). The class must be on the classpath.

The Saxon namespace URI http://saxon.sf.net/ is recognised as a special case. In most cases it causes the function to be loaded from the class net.sf.saxon.functions.Extensions but in a few cases, such as saxon:evaluate, the function is recognized by the compiler as if it were a built-in function. The various EXSLT namespaces are also recognized specially.

In XSLT, the system function function-available(String name) returns true if there appears to be a method available with the right name. The function also has an optional second argument to test whether there is a method with the appropriate number of arguments. However, it is not possible to test whether the arguments are of appropriate types. If the function name is "new" it returns true so long as the class is not an abstract class or interface, and so long as it has at least one constructor.

Identifying the Java constructor, method, or field

The local name used in the XPath function call determines which constructor, method, or field of the Java class is invoked. This decision (called binding) is always made at the time the XPath expression is compiled. If methods are overloaded, static type information will be used to decide between them.