Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Java method with Variable Argument in XSLT

I have a Java method with variable argument which I need to call from XSLT (1.0). But it doesn't work, it keeps failing with the following error:

javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet

However, if I expand the variable argument, it works!

Example:

 public static String getValue(String key, String... args) {  // this is what I want, but doesn't work

 public static String getValue(String key, String args1) { // this works

 public static String getValue(String key, String args1, String args2) { // this works

In XSLT:

<xsl:value-of select="myjavaclass:getValue('MyKey','Arg1')"/>

<xsl:value-of select="myjavaclass:getValue('MyKey','Arg1','Arg2')"/>

So, does anyone know if I can use Java method with variable argument in XSLT? I hope I don't have to create different methods for each number of argument.

Thank you much!

like image 663
elefant Avatar asked Sep 28 '26 11:09

elefant


2 Answers

As far as reflection is concerned a varargs method like

public static String getValue(String key, String... args)

is a method with two parameters, the first is a String and the second is a String[]. When you call a varargs method from Java code the compiler generates bytecode to bundle up the variable args into an array, but when you're calling by reflection, as will be the case here, you have to build the array yourself.

So the question becomes, does your XSLT processor provide any way to pass parameters of type String[] from XSLT to Java? In the case of Xalan (the default javax.xml.transform implementation if you don't have another one on your classpath) I believe the answer is no, except in the special situation where the String[] was returned by another extension function.

like image 195
Ian Roberts Avatar answered Sep 30 '26 02:09

Ian Roberts


Since your first argument is also of type String, I think its causing the issue.

Try

     public static String getValue(String... args) {
           String key = args[0];
           String arg1 = args[1];
           .....  
     }
like image 26
Yogendra Singh Avatar answered Sep 30 '26 02:09

Yogendra Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!