}
// get the actual arguments
final Sequence args[] = getArguments(contextSequence, contextItem);
AccessibleObject bestMethod = candidateMethods.get(0);
int conversionPrefs[] = getConversionPreferences(bestMethod, args);
for (AccessibleObject nextMethod : candidateMethods) {
int prefs[] = getConversionPreferences(nextMethod, args);
for (int j = 0; j < prefs.length; j++) {
if (prefs[j] < conversionPrefs[j]) {
bestMethod = nextMethod;
conversionPrefs = prefs;
break;
}
}
}
// LOG.debug("calling method " + bestMethod.toString());
Class<?> paramTypes[] = null;
boolean isStatic = true;
if (bestMethod instanceof Constructor<?>)
{paramTypes = ((Constructor<?>) bestMethod).getParameterTypes();}
else {
paramTypes = ((Method) bestMethod).getParameterTypes();
isStatic = Modifier.isStatic(((Method) bestMethod).getModifiers());
}
final Object[] params = new Object[isStatic ? args.length : args.length - 1];
if (isStatic) {
for (int i = 0; i < args.length; i++) {
params[i] = args[i].toJavaObject(paramTypes[i]);
}
} else {
for (int i = 1; i < args.length; i++) {
params[i - 1] = args[i].toJavaObject(paramTypes[i - 1]);
}
}
Sequence result;
if (bestMethod instanceof Constructor<?>) {
try {
final Object object = ((Constructor<?>) bestMethod).newInstance(params);
result = new JavaObjectValue(object);
} catch (final IllegalArgumentException e) {
throw new XPathException(this,
"illegal argument to constructor "
+ bestMethod.toString()
+ ": "
+ e.getMessage(),
e);
} catch (final Exception e) {
if (e instanceof XPathException)
{throw (XPathException) e;}
else
{throw new XPathException(this,
"exception while calling constructor "
+ bestMethod.toString()
+ ": "
+ e.getMessage(),
e);}
}
} else {
try {
Object invocationResult;
if (isStatic)
{invocationResult = ((Method) bestMethod).invoke(null, params);}
else {
invocationResult =
((Method) bestMethod).invoke(
args[0].toJavaObject(myClass),
params);
}
result = XPathUtil.javaObjectToXPath(invocationResult, getContext());
} catch (final IllegalArgumentException e) {
throw new XPathException(this,
"illegal argument to method "
+ bestMethod.toString()
+ ": "
+ e.getMessage(),
e);
} catch (final Exception e) {
if (e instanceof XPathException)
{throw (XPathException) e;}
else
{throw new XPathException(this,
"exception while calling method "
+ bestMethod.toString()
+ ": "
+ e.getMessage(),
e);}
}
}