JBoss.org Community Documentation

22.3. Attaching extra information

Since each instance of DeploymentContext contains generic deployment information we need a way to store and retrieve additional information generated during the deployment process. This is done using the DeploymentUnit wrapper which extends the MutableAttachments interface:


public interface DeploymentUnit extends MutableAttachments
{
    ...
}

public interface MutableAttachments extends Attachments
{
   Object addAttachment(String name, Object attachment);
   <T> T addAttachment(String name, T attachment, Class<T> expectedType);
   <T> T addAttachment(Class<T> type, T attachment);

   Object removeAttachment(String name);
   <T> T removeAttachment(String name, Class<T> expectedType);
   <T> T removeAttachment(Class<T> type);

   void setAttachments(Map<String, Object> map);

   void clear();

   int getChangeCount();
   void clearChangeCount();
}

As you can see the MutableAttachments operations allow you to store arbitrary objects (referred to as attachments) inside a map using a String for the key. For convenience you can pass in the type of the object instead of a string and the return value of type.getName() will be used as the key. If you pass in a type for the key, or you specify an expectedType argument, then the return value will be cast to an object of that type.

If you wish to retrieve any objects then you can use operations from the Attachments interface:


public interface Attachments extends Serializable
{
   Map<String, Object> getAttachments();

   Object getAttachment(String name);
   <T> T getAttachment(String name, Class<T> expectedType);
   <T> T getAttachment(Class<T> type);
   
   boolean isAttachmentPresent(String name);
   boolean isAttachmentPresent(String name, Class<?> expectedType);   
   boolean isAttachmentPresent(Class<?> type);

   boolean hasAttachments();
}

Again if you pass a type for the key, or specify an expectedType argument, then the return value will be cast to an object of that type. In the case of the isAttachmentPresent() methods the return value is only true if both the object can be located using the key and it can be cast to the specified type.

DeploymentUnit also contains a convenience method that allows you to retrieve all objects of a particular type from the map of attachments:


public interface DeploymentUnit extends MutableAttachments
{
    ...
   <T> Set<? extends T> getAllMetaData(Class<T> type);
    ...
}