复制JMS消息属性

时间:2010-09-17 15:15:15

标签: properties jms

是否有一种简单的方法可以将属性从一个JMS消息复制到另一个JMS消息?

我可以想象这样的事情:

private void copyMessageProperties (Message msg1, Message msg2) throws JMSException {
    Enumeration srcProperties = msg1.getPropertyNames();
    while (srcProperties.hasMoreElements()) {
        String propertyName = (String) srcProperties.nextElement ();

        // Now try to read and set
        try {
            Object obj = msg1.getObjectProperty (propertyName);
            msg2.setObjectProperty (propertyName, obj);
            continue;
        } catch (Exception e) {}
        try {
            String str = msg1.getStringProperty (propertyName);
            msg2.setStringProperty (propertyName, str);
            continue;
            ...
        }
    }
}

但这非常难看。必须有另一种方式

1 个答案:

答案 0 :(得分:9)

这是我最终解决的解决方案......

@SuppressWarnings("unchecked")
private static HashMap<String, Object> getMessageProperties(Message msg) throws JMSException 
{
   HashMap<String, Object> properties = new HashMap<String, Object> ();
   Enumeration srcProperties = msg.getPropertyNames();
   while (srcProperties.hasMoreElements()) {
       String propertyName = (String)srcProperties.nextElement ();
       properties.put(propertyName, msg.getObjectProperty (propertyName));
   }
   return properties;
}

private static void setMessageProperties(Message msg, HashMap<String, Object> properties) throws JMSException {
    if (properties == null) {
        return;
    }
    for (Map.Entry<String, Object> entry : properties.entrySet()) {
        String propertyName = entry.getKey ();
        Object value = entry.getValue ();
        msg.setObjectProperty(propertyName, value);
    }
}