Gavin makes good points here -- this is all infrastructure that's needed for annotation processing. And, I agree with Bob that in Java 5, this sort of checking should be done by writing annotation processors that run via apt (or even at run time). A great place to start would be to have available in Open Source a framework that provides:
- a set of meta-meta annotations
- a framework for validating them
- a framework for adding custom, build-time annotation checks
Apache
Beehive has a good start here as part of the Controls sub-project which is a generalized framework for building annotated JavaBeans. Controls provides meta-meta annotations like:
@
AllowExternalOverride()
@
MembershipRule(value=MembershipRuleValues.AT_LEAST_ONE)
@
AnnotationMemberTypes.Date()
... and so on ...
that can be used on annotation interfaces like:
public @interface LastChanged {
@AnnotationMemberTypes.Date(format="MM/dd/yyyy")
public String date();
}
to provide additional annotation constraints and metadata. These annotations are checked at build-time using a custom annotation processor to enforce semantic checks. The set of meta-meta annotations could easily be extended to support the constraints Gavin describes. The framework also provides a generalized mechanism for adding a custom annotation "checker" that can be implemented by the developer of a Control's annotation interface.
As a simple example, the annotation checker for Beehive's JdbcControl is
here. This custom checker is used to check annotations like:
@JdbcControl.SQL(statement="select id, name, ssn from employees where id={id}")
public Employee getEmployeeByName(String id);
to ensure that the SQL statement is not empty, that the "{id}" substitution matches a formal argument name, and (though it's not implemented) could even parse and validate the SQL itself. A custom checker is declared simply by adding this to a Control interface:
@ControlInterface(checker=JdbcControlChecker.class)
While this infrastructure is currently coupled to the Beehive Controls runtime, it embodies many concepts useful for annotation processing++. Speaking for myself, it would be interesting to discuss how to share some of the annotations and infrastructure here and to look at standardization in the future. Any interest in this?
Personally, my biggest gripe about the APT tool in JDK 5 is that it's not possible to both generate a source file at annotation processing time *and* use the type information in the generated file in the same apt process. This problem forces some annotation processing scenarios to be two-pass and precludes using apt for compilation. Working around this problem can necessitate build-time weirdness like:
- process annotations in some source files
- generate source files
- process annotations in more source files
- generate source files
- compile
instead of:
- process annotations, generate source files, and compile
Blog post forthcoming on this topic.
Looking forward to this being fixed in Java 6. :)
Eddie