Skip to content

Adding, getting and removing attributes

Elliot Ford edited this page Apr 7, 2015 · 11 revisions

What is an AttributeContainer?

An AttributeContainer (API docs) is a store for attributes. An Entity is an AttributeContainer although the container is useful on its own. JALSE offers a default implementation of AttributeContainer, DefaultAttributeContainer, which can also be used to create your own Entity implementation.

AttributeContainer container = new DefaultAttributeContainer();

AttributeContainer uses a attribute name with an AttributeType or NamedAttributeType for a unique key (see Creating an AttributeType). When attributes are added, changed or move they trigger listener events (see Creating an AttributeListener).

Adding attributes

Adding an attribute assigns a value to the name and type key. This will replace the previously associated value. These should not be null!

String previous = container.addAttribute("username", Attributes.STRING_TYPE, "Ellzord");

or

Optional<String> optPrevious = container.addOptAttribute("username", Attributes.STRING_TYPE, "Ellzord");

There are NamedAttributeType equivalents: container.addAttribute(NamedAttributeType, Object) and container.addOptAttribute(NamedAttributeType, Object).

Getting attributes

Gets an attribute (if any) associated to the name and type key.

String value = container.getAttribute("username", Attributes.STRING_TYPE);

or

Optional<String> optValue = container.getOptAttribute("username", Attributes.STRING_TYPE);

There are NamedAttributeType equivalents: container.getAttribute(NamedAttributeType) and container.getOptAttribute(NamedAttributeType)

There are also container.hasAttribute(String, AttributeType) and container.hasAttribute(NamedAttributeType) for convenience.

Removing attributes

Removes an attribute (if any) associated to the name and type key.

String oldValue = container.removeAttribute("username", Attributes.STRING_TYPE);

or

Optional<String> optOldValue = container.removeOptAttribute("username", Attributes.STRING_TYPE);

There are NamedAttributeType equivalents: container.removeAttribute(NamedAttributeType) and container.removeOptAttribute(NamedAttributeType).

Using multiple attributes

An AttributeContainer can be used much like a Collection.

Total attribute count: container.getAttributeCount() Stream attributes: container.StreamAttributes() All attributes (Set): container.getAttributes() All attribute names: container.getAttributeNames() All attribute types for a name: container.getAttributeTypes("username") Add all attributes from another container: container.addAllAttributes(otherContainer) Remove all attributes: container.removeAttributes()

Clone this wiki locally