@Override Annotation 他的具体解析器代码哪里?可否具体解释下了。
知道他是反射机制解析的,具体代码在那里呢??

解决方案 »

  1.   

    JDK API哪有那个哦,他只有接口,没有实现呀
      

  2.   

    Retention(RetentionPolicy.SOURCE)
    编译时不保留注释,只作为编写源码时使用,所以不可使用反射处理
      

  3.   


    /*
     * @(#)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 {
    }
      

  4.   

    晕,我要具体实现,这个当然知道的了,好像是tools.jar中com.sun.javac.process...下的那个类,谁能解释下具体实现(反射过程)...
      

  5.   

    这是 Java 编译器处理的,这已经远远超出了 Java 反射的范畴,是从语法及语义上进行处理的。
      

  6.   

    有兴趣的话可以去看一下 javac 编译器的实现,非常复杂,拥有 108 个类 2MB 多的源代码。
      

  7.   

    具体的解析处理在 com.sun.tools.javac.comp.Check 类的这个方法处理的:/** 
     * 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 万余行源代码。