2010-09-17 40 views
6

Có cách nào dễ dàng sao chép các thuộc tính từ một tin nhắn JMS này sang một tin nhắn JMS khác không?Sao chép các thuộc tính Tin nhắn JMS

tôi có thể tưởng tượng một cái gì đó như thế này:

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; 
      ... 
     } 
    } 
} 

Nhưng đó là nghiêm túc xấu xí. Phải có một cách khác

Trả lời

9

Đây là giải pháp tôi đã kết thúc với ...

@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

Một LinkedHashMap là tốt hơn để giữ gìn trật tự – mcoolive

Các vấn đề liên quan