2010-09-17 170 views
6

是否有將屬性從一個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; 
      ... 
     } 
    } 
} 

但是,這是嚴重的醜陋。必須有另一種方式

回答

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); 
    } 
} 
+1

LinkedHashMap中是更好地維護秩序 – mcoolive 2015-12-14 02:10:57