Java comes with annotation processor capabilities starting in Java 6: Source Code Analysis . (Technically, this is part of Java 5, but Java 6 integrated it into the compiler phase, and not into a special tool). Sun provides this Getting Started Guide .
The comment handler is processed by the compiler when creating the project and may throw errors in the same way as the compiler does. This is a neat way to provide more rules than Java indicates.
Here is an example of a Processor that would perform the required check:
@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes("*")
public class CheckMethodOverride extends AbstractProcessor {
private static boolean hasMethod(TypeElement clazz, String methodName, int arity) {
for (ExecutableElement method :
ElementFilter.methodsIn(clazz.getEnclosedElements())) {
if (method.getSimpleName().equals(methodName)
&& method.getParameters().size() == arity)
return true;
}
return false;
}
TypeMirror interfaceToCheck;
@Override
public void init(ProcessingEnvironment env) {
interfaceToCheck = env.getElementUtils().getTypeElement("com.notnoop.myinterface").asType();
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) {
for (TypeElement e :
ElementFilter.typesIn(roundEnvironment.getRootElements())) {
if (this.processingEnv.getTypeUtils()
.isSubtype(e.asType(), interfaceToCheck)
&& (!hasMethod(e, "equals", 0)
|| !hasMethod(e, "hashCode", 0))) {
processingEnv.getMessager().printMessage(Kind.ERROR,
"Class " + e + " doesn't override hashCode or equals", e);
}
}
return true;
}
}
( -processor com.notnoop.CheckMethodOverride ) META-INF/services , (com.notnoop.CheckMethodOverride). META-INF ( maven).
. , IDE.