Recipe16.6.Extending Compilation


Recipe 16.6. Extending Compilation

Problem

You want to extend the capabilities of the compiler to enforce application specific rules.

Solution

Use the declare error or declare warning statement to specify conditions that should raise a compiler error or warning respectively.

Discussion

AspectJ supports advising most of the Java system but perhaps the most interesting and odd construct is the Java compiler. Example 16-10 shows how to declare a new error and warning that will be raised by the compiler if the specified condition is found within the application being compiled.

Example 16-10. Using aspects to declare new warnings and errors that can be raised by the compiler
public aspect CompilationAdviceRecipe  {    declare error : call(void ProtectedAccessClass.setValue(int))       && !this(MyClass)        : "Must only set the ProtectedAccessClass.value from a MyClass object";    declare warning : call(int ProtectedAccessClass.getValue( ))       && !this(MyClass)        : "Should only be reading ProtectedAccessClass.value from a MyClass          object"; }

The capability to enforce new rules regarding what Java constructs are allowed and how they should be used is useful when you are potentially creating an application that may have changing needs depending on its target environment and as to what functionality it is allowed to expose. This allows you to define system policy warnings and to guide developers in their implementations.

The error and warning messages must be simple, declared string literals. You cannot reference any other part of the software architecture, even static pieces of the structure, from within these messages.


See Also

Recipe 17.5 shows how this form of warning is used to indicate to developers that they are breaking the rules of Builder design pattern; for real-world examples of using declare error and declare warning to enforce design constraints and general developer guidance, take a look at the aTrack bug-tracking project available at https://atrack.java.net.



AspectJ Cookbook
Aspectj Cookbook
ISBN: 0596006543
EAN: 2147483647
Year: 2006
Pages: 203
Authors: Russ Miles

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net