Why?

In many cases an attribute can only be applied to certain elements, and its parameters must satisfy some set of constraints. For example, suppose we have an attribute that declares transaction metadata:

/**
 * @@TransactionDeclaration (TransactionDeclaration.EXPLICIT)
 */

Now, the rule is that if a class has a TransactionDeclaration.EXPLICIT setting, then all methods must have a @@TransactionLevel attribute. For example, this class is valid:

/**
 * @@TransactionDeclaration(TransactionDeclaration.EXPLICIT)
 */
class ValidClass {

    /**
     * @@TransactionLevel(TransactionLevel.SERIALIZABLE)
     */
    void methodOne() { ... }

    /**
     * @@TransactionLevel(TransactionLevel.READ_UNCOMMITTED)
     */
    void methodTwo() { ... }

}

While this one is not, since methodTwo does not define a @@TransactionLevel.

/**
 * @@TransactionDeclaration(TransactionDeclaration.EXPLICIT)
 */
class ValidClass {

    /**
     * @@TransactionLevel(TransactionLevel.SERIALIZABLE)
     */
    void methodOne() { ... }

    void methodTwo() { ... }

}

The attribute-validator task enables you to check the consistency of attributes at compile-time.

The attribute-validator Task

The attribute-validator task is run like this from your Ant file:

<attribute-validator jarFile="myclasses.jar">
    <classpath>
        ...
    </classpath>
    <validator class="my.Validator"/>
    <validator class="my.other.Validator"/>
</attribute-validator>
Parameter Required Description
jarFile yes The jar file whose classes should be validated.
Element Required Description
classpath yes The classpath to use when loading classes from the jar file.
validator yes One or more validators, which are classes implementing the AttributeValidator interface.

Writing Your Own Validation Rules

Writing a validation rule simply means implementing the AttributeValidator interface in a class. For example, this AttributeValidator will check that there are no more than three class attributes given to each class.

public class MyValidator 
    implements AttributeValidator {

    public void validate (Set classes) throws ValidationException {
        Iterator iter = classes.iterator ();
        while (iter.hasNext ()) {
            Class clazz = (Class) iter.next ();
            if (Attributes.getAttributes (clazz).size () > 3) {
                throw new ValidationException (clazz, 
                    "Classes must have at most three attributes!");
            }
        }
    }

}