Calling Java Instance-Level Methods

Instance-level methods (that is, non-static methods) are called by supplying an extra first argument of type Java Object which is the object on which the method is to be invoked. A Java Object is usually created by calling an extension function (e.g. a constructor) that returns an object; it may also be passed to the style sheet as the value of a global parameter. Matching of method names is done as for static methods. If there are several methods in the class that match the localname, the system again tries to find the one that is the best fit, according to the types of the supplied arguments (see Choosing among overloaded methods.

For example, the following XSLT stylesheet prints the date and time. (In XSLT 2.0, of course, this no longer requires extension functions, but the example is still valid.)

<xsl:stylesheet version="1.0" xmlns:xsl="" xmlns:date="java:java.util.Date"> <xsl:template match="/"> <html> <xsl:if test="function-available('date:to-string') and function-available('date:new')"> <p><xsl:value-of select="date:to-string(date:new())"/></p> </xsl:if> </html> </xsl:template> </xsl:stylesheet>

The equivalent in XQuery is:

declare namespace date="java:java.util.Date"; <p>{date:to-string(date:new())}</p>

As with static methods, an instance-level Java method called as an extension function may have an extra first argument of class net.sf.saxon.expr.XPathContext. This argument is not supplied by the calling XPath or XQuery code, but by Saxon itself. The XPathContext object provides methods to access many internal Saxon resources, the most useful being getContextItem() which returns the context item from the dynamic context. The XPathContext object is not available with constructors.

If any exceptions are thrown by the method, or if a matching method cannot be found, processing of the stylesheet will be abandoned. If the tracing option -T has been set on the command line, a full stack trace will be output. The exception will be wrapped in a TransformerException and passed to any user-specified ErrorListener object, so the ErrorListener can also produce extra diagnostics.

It is also possible to use the reflexive call mechanism to call instance-level methods of the implementation classes for XDM values. For example, the following gets the current Julian instant as a decimal number:

<xsl:value-of select="d:toJulianInstant(current-dateTime())" xmlns:d="java:net.sf.saxon.value.DateTimeValue"/>

This will only work if the value of the expression (current-dateTime() in this example) is implemented internally as an instance of the class defined in the namespace used to invoke the method. Using this mechanism successfully therefore requires some knowledge of the Saxon internals.