Skip to content

Creating an AttributeType

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

What is an AttributeType?

An AttributeType defines what Type (or parent type) the attribute value has. An attribute value type is used along with an attribute name to determine a field within an AttributeContainer - such as username:String = Ellzord.

Why is AttributeType an abstract class?

AttributeType is abstract because full generic type information for an instance is not possible to get unless somewhere in the type tree the generic type (in this case T) is defined. JALSE also uses this generic information to tell the difference between types such as Collection<String> and Collection<Integer>. AttributeType has some final methods to ensure it will always be uniqueness can always be determined (using the value type).

Creating an AttributeType instance

Attribute type is abstract but is complete so creating an anonymous class instance is all that has to be done. Here we create a new String type:

AttributeType<String> strType = new AttributeType<String>(){};

The Attributes (API docs for Attributes) utility provides all of the primitive types (Attributes.STRING_TYPE could be used in place of the above).

For simple types (types with no type parameters) Attributes.newTypeOf(Class) can be used:

AttributeType<UUID> idType = Attributes.newTypeOf(UUID.class);

For when type erasure is not possible but the Type is available Attributes.newUnknownType(Type) can be used:

Type type; // Some (generic) type.
AttributeType<Object> unknownType = Attributes.newUnknownType(type);

What is a NamedAttributeType?

A NamedAttributeType is a combination of AttributeType and the attribute name. Named attribute types are convenient and allow for attribute type information to be stored and reused (instead of making a new instance each type for non-primitive types). AttributeContainer provides methods that take both String with AttributeType and NamedAttributeType as arguments.

Creating a NamedAttributeType

NamedAttributeType like AttributeType can be used as a key (name and AttributeType used to determine uniqueness). Creating a NamedAttributeType is much more simple:

NamedAttributeType<String> usernameType = new NamedAttributeType<>("username", Attributes.STRING_TYPE);

Attributes provides methods to create named attribute types for all of the primitive types (Attributes.newNamedStringType("username") could be used in place of the above).

For named simple types Attributes.newNamedTypeOf(String, Class) can be used:

NamedAttributeType<UUID> userIDType = Attributes.newNamedTypeOf("userID", UUID.class);

For named unknown types Attributes.newNamedUnknownType(Type) can be used:

Type type; // Some (generic) type.
NamedAttributeType<Object> masterType = Attributes.newNamedUnknownType("master", type);

Clone this wiki locally