2

我正在使用名为 Mirth(3.6 版)的产品来执行转换代码。它似乎没有交互式调试器,所以任何人都可以解释为什么目标转换中的以下代码只会从 IF 语句而不是 SWITCH 语句中记录?可以在 Eclipse 中运行的常规 java 中完美运行,但此代码在 Mirth 使用的 JavaScript 引擎中执行(如果我没记错的话,Rhino)。

for each (node in msg['PID'].children()) 
{
    if(node.name() == "PID.3")
        {
        logger.info("IF Succeeded");
    }

    switch(node.name())
    {
        case "PID.3": 
             logger.info("SWITCH Succeeded"); // This line never logs
             break;
    }
}
4

1 回答 1

3

这是 Mirth Connect 的常见问题,因为它使用 Rhino 作为引擎(使用 java 和 javascript)。Switch 语句不适用于 Java String 对象 简单的解决方案是通过将空字符串连接到有问题的字符串(即 str + ''),将任何未知字符串类型转换为原生 JS 字符串

// See in action
for each (node in msg['PID'].children()) 
{
    var nodeName = node.name();
    if (nodeName != "PID.3")
    {
       continue;
    }
    var type = typeof(nodeName);

    logger.debug('NodeName: ' + nodeName + '; Type: ' + type);
    if (type == 'object') {
        logger.debug('Type is object');
        if (nodeName instanceof String) {
            logger.debug('Object is Java String instance');
        } else {
            logger.debug('Object is not Java String instance');
        }
    } else if (type === 'string') {
        logger.debug('Type is JS string.');
    } else {
        logger.debug('Type is not object or string. Type: ' + type);
    }

    // Works with String object or JS string
    if (nodeName == "PID.3")
    {
       logger.info("IF Succeeded");
    }

    // Only works with JS string
    switch (nodeName)
    {
        case "PID.3": 
            logger.info("SWITCH Succeeded"); // This line never logs
            break;
        default:
            logger.info("SWITCH not matched: " + nodeName);
            break;
    }

    logger.debug('Convert to JS string');
    nodeName = nodeName + '';
    type = typeof(nodeName);
    logger.debug('Converted Type: ' + type);
    if (type == 'object') {
        logger.debug('Converted Type is object');
        if (nodeName instanceof String) {
            logger.debug('Converted Object is String instance');
        } else if (nodeName instanceof string) {
            logger.debug('Converted Object is string instance');
        } else {
            logger.debug('Converted Object is not Java String instance');
        }
    } else if (type === 'string') {
        logger.debug('Converted Type is JS string.');
    } else {
        logger.debug('Converted Type is not object or string. Type: ' + type);
    }

    switch(nodeName)
    {
        case "PID.3": 
            logger.info("SWITCH with js string Succeeded");
            break;
        default:
            logger.info("SWITCH with js string not matched: " + nodeName);
            break;
    }
    break;
}
于 2018-06-26T16:16:43.770 回答