/* * @(#)Override.java 1.6 05/11/17 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */package java.lang;import java.lang.annotation.*;/** * Indicates that a method declaration is intended to override a * method declaration in a superclass. If a method is annotated with * this annotation type but does not override a superclass method, * compilers are required to generate an error message. * * @author Joshua Bloch * @since 1.5 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface Override { }
编译时不保留注释,只作为编写源码时使用,所以不可使用反射处理
/*
* @(#)Override.java 1.6 05/11/17
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/package java.lang;import java.lang.annotation.*;/**
* Indicates that a method declaration is intended to override a
* method declaration in a superclass. If a method is annotated with
* this annotation type but does not override a superclass method,
* compilers are required to generate an error message.
*
* @author Joshua Bloch
* @since 1.5
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
* Check an annotation of a symbol.
*/
public void validateAnnotation(JCAnnotation a, Symbol s) {
validateAnnotation(a); if (!annotationApplicable(a, s))
log.error(a.pos(), "annotation.type.not.applicable"); // syms.overrideType 的值设置在 com.sun.tools.javac.code.Symtab 类中
// overrideType = enterClass("java.lang.Override");
if (a.annotationType.type.tsym == syms.overrideType.tsym) {
if (!isOverrider(s)) // 由这个进行判断的
// method.does.not.override.superclass 对应的中文资源 key 的内容是
// 方法不会覆盖或实现超类型的方法
log.error(a.pos(), "method.does.not.override.superclass");
}
}紧接着的代码就是 isOverrider:/** Is s a method symbol that overrides a method in a superclass? */
boolean isOverrider(Symbol s) {
if (s.kind != MTH || s.isStatic())
return false;
MethodSymbol m = (MethodSymbol)s;
TypeSymbol owner = (TypeSymbol)m.owner;
for (Type sup : types.closure(owner.type)) {
if (sup == owner.type)
continue; // skip "this"
Scope scope = sup.tsym.members();
for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
return true;
}
}
return false;
}
这都是按语法分析来完成的,属于非常底层的字符串解析,是由编译器直接在源代码上进行处理的,而反射是通过字节码进行处理的。编译器的源代码非常复杂,看不了几个类就会晕掉。何况这 108 个类文件 6 万余行源代码。