Java는 Java 6부터 시작하여 주석 처리 기능을 제공합니다 (예 : Source Code Analysis).(기술적으로는 Java 5의 일부이지만 Java 6에서는 특수 도구가 아닌 컴파일러 단계에 통합했습니다.) Sun에서 제공하는 Getting Started guide.
주석 프로세서는 프로젝트를 빌드하는 동안 컴파일러에 의해 호출되고 컴파일러에서와 마찬가지로 오류가 발생할 수 있습니다. Java가 규정 한 것보다 더 많은 규칙을 시행하는 깔끔한 방법입니다. 또는 META-INF/services
파일을 추가 (컴파일러 옵션에 -processor com.notnoop.CheckMethodOverride
을 추가하여) 주석 프로세서가 컴파일러 옵션에 직접 지정할 수 있습니다
@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes("*")
public class CheckMethodOverride extends AbstractProcessor {
// returns true if the class has a method with the specified method name
// and specified number of parameters
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;
}
// the interface whose subclasses must override hashCode and equals
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;
}
}
: 여기
당신이 원하는 검사를 수행 할 샘플 프로세서입니다 프로세서 이름 (
com.notnoop.CheckMethodOverride
)이 들어있는 classpath에 추가하십시오. forlder
META-INF
은 프로젝트의 루트 소스 디렉토리 (또는 maven을 사용하는 경우 자원 디렉토리)에 살 수 있습니다.
모든 명령 줄 컴파일러에서 작동합니다. 내가 IDE에서 그것을 활성화하는 방법을 모르겠다.
나는 이것을 완전히 이해하지는 못했지만 놀랍고, OP의 문제에 대한 우아한 해결책이 될 것입니다. +1. –
+1 : 우아한 해결책 !!! 나는 그것을 시도 할 것이다 ... –
이것은 주석에서 "클래스 리터럴을 런타임 유형 토큰으로 사용하는"좋은 예이다. http://java.sun.com/docs/books/tutorial/extra/generics/literals.html . 그것은 Neal Gafter의 "Super Type Tokens"를 연상케합니다. http://gafter.blogspot.com/2006/12/super-type-tokens.html – trashgod