当前位置: 代码网 > it编程>编程语言>Java > Java注解处理器实战(附详细示例代码)

Java注解处理器实战(附详细示例代码)

2025年10月10日 Java 我要评论
注解处理器注解强大的地方在于: 我们可以在运行时或者编译时处理注解. 在编译时或者运行时处理注解的机制都可以称为一个注解处理器.注解处理器的类型注解处理器的类型分为两大类:运行时处理器: 这种机制是在

注解处理器

注解强大的地方在于: 我们可以在运行时或者编译时处理注解. 在编译时或者运行时处理注解的机制都可以称为一个注解处理器.

注解处理器的类型

注解处理器的类型分为两大类:

  • 运行时处理器: 这种机制是在程序运行时利用反射机制去处理注解.
  • 编译时处理器: 这种机制是在程序编译时利用javac提供的一个apt工具来处理注解.

运行时处理器的特点: 该机制基于反射机制, 因此灵活性很大, 但是却相对耗性能. 编译时处理器的特点:这种方法是在编译时处理注解, 因此不存在性能的问题, 但是灵活性也相对比较低.

在已有的开源库实现中, 普遍是结合编译时处理器和反射机制这两种方法. 举个例子: butterknife. 它是一个view注入的库. 内部实现的原理: 编译时利用apt生成findviewbyid等一些列模板代码, 然后在运行时利用反射去实例生成的模板代码类, 这样完成了一次注入. 从这里可以看出, butterknife并没有完全基于编译时注解处理器. 而是加了反射.

这样做的好处: 开发者不需要手动实例apt生成的类. 换句话说: 开发者不需要了解生成类的命令规则. 也许你可能会觉得利用反射会耗性能. 但是仔细想想, 如果没有利用反射的话, 开发者都需要手动编译, 然后再实例化生成的类. 这个过程也是挺繁琐的. 而且, 库内部是有做相应的缓存的, 所以耗的性能还是相对比较低的.

对于反射的利用, 应该适当使用, 而不是避而不用或者滥用.

接下来, 讲讲apt的一些知识, 最后再仿写一个简单的butterknife作为实战.

abstractprocessor

开发注解处理器的第一个步骤就是继承abstractprocessor. 然后重写其四个方法:

  • public synchronized void init(processingenvironment processingenvironment): 这个方法一般是做一些初始化的工作.
  • public sourceversion getsupportedsourceversion(): 该处理器所支持的jdk版本, 一般是支持到最新: sourceversion.latestsupported().
  • public set<string> getsupportedannotationtypes(): 你所要处理的注解的类型.
  • public boolean process(set<? extends typeelement> set, roundenvironment roundenvironment): 处理注解的方法. 这个是我们主要实现的方法. 返回值表示当前这个注解类型是否需要被随后的注解处理器处理. true表示不需要, false表示后面的注解处理器可能会对本次处理的注解.

认识这4个方法后, 我们还需要熟悉一下编写处理器涉及到的一些概念和api.

processingenvironment

processingenvironment是在init方法传入的. 它表示apt框架的一个处理时上下文. 这个类主要是提供一些工具类. 详细看下面代码注释:

public interface processingenvironment {
    //获取外部配置的参数
    map<string,string> getoptions();
    //获取messager对象, 用于打印一些日志
    messager getmessager();
    //获取filer对象, 该对象用于创建文件
    filer getfiler();
    //获取elements, 它包含处理element的一些工具方法
    elements getelementutils();
    //获取types, 它包含处理typemirror的一些工具方法
    types gettypeutils();
    sourceversion getsourceversion();
    locale getlocale();
}

roundenvironment

当apt启动时, 它将会扫描源文件, 然后进入process方法处理, 如果这个过程生成了新的文件的话, 新文件会被apt再次作为输入, 接着process会被apt再次调用, 如此循环下去, 直到没有新的文件产生. roundenvironment为处理轮次的上下文环境. 下面是roundenvironment的方法简单介绍:

public interface roundenvironment {
    //用于判断是否处理完了, 只有当没有新文件生成时, 证明已经处理完了, 才会返回true
    boolean processingover();
    //上一次处理是否存在错误
    boolean errorraised();
    //获取前一次处理的根元素集合
    set<? extends element> getrootelements();
    //获取被指定的类型元素标注的元素集
    set<? extends element> getelementsannotatedwith(typeelement a);
    //获取被指定的注解标注的元素集
    set<? extends element> getelementsannotatedwith(class<? extends annotation> a);
}

element

element代表java静态语言结构的元素. 这样听起来可能有点难以理解, 不过看下面的例子就会很好理解了:

package com.desperado.processors; //packageelement
public class test { //typeelement: 代表类或接口元素
    private int xixi; //variableelement:
    public test() { //executableelement
    }
    public void haha(string arg) { //haha方法为texecutableelement
        int v; //variableelement
    }
}
  • typeelement: 代表类或接口元素
  • variableelement: 代表字段, 枚举常量, 方法或构造函数的参数, 局部变量, 资源变量和异常参数.
  • packageelement: 代表包元素
  • executableelement: 代表的方法, 构造方法,和接口或者类的初始化块.

declaredtype, typeelement和typemirror

typeelement表示类或接口元素, 可以从中获取类名, 但是不能获得类本身的信息, 比如父类.

typemirror: 表示java语言中的类型, 其中包括: 基本类型, 声明类型(类类型和接口类型), 数组类型, 类型变量和空类型. 也代表通配类型参数,可执行文件的签名和返回类型.

declaredtype: 代表声明的类型, 类类型还是接口类型,当然也包括参数化类型,比如set,也包括原始类型.

开发一个注解处理器

掌握了上面的概念后, 我们开始来开发一个仿butterknife的注解处理器.

步骤

  • 继承abstractprocessor并重写其中的四个方法.
  • 注册注解处理器.

继承abstractprocessor

@autoservice(processor.class)
public class viewbindingprocessor extends abstractprocessor {
    private types types;
    private filer filer;
    private messager messager;
    private elements elements;
    @override
    public synchronized void init(processingenvironment processingenvironment) {
        super.init(processingenvironment);
        types = processingenvironment.gettypeutils();
        filer = processingenvironment.getfiler();
        messager = processingenvironment.getmessager();
        elements = processingenvironment.getelementutils();
    }
    @override
    public boolean process(set<? extends typeelement> set, roundenvironment roundenvironment) {
        //process
        return true;
    }
    @override
    public sourceversion getsupportedsourceversion() {
        return sourceversion.latestsupported();
    }
    @override
    public set<string> getsupportedannotationtypes() {
        set<string> annotations = new linkedhashset<>();
        annotations.add(bindview.class.getcanonicalname());
        return annotations;
    }
}

在getsupportedannotationtypes()中, 我们直接返回了需要处理的注解的全限定名称集合.

注册处理器

写好的处理器还需要处理告诉javac, 让它编译时运行我们的处理器. 注册的步骤为: 在项目新建一个resources目录, 然后在resources内新建这样的目录结构: /meta-inf/services/. 最后在services中新建文件: javax.annotation.processing.processor. 并且在文件上填写你的处理器的全路径名称. 例如: com.desperado.processors.viewbindingprocessor.

其实还有一种更为简单的方法. 添加com.google.auto.service:auto-service:1.0-rc2这个库(google开源的). 然后在你的处理器上添加注解: @autoservice(processor.class). 这样, 编译时就会自动帮我们生成注册文件.

如何组织处理器结构

为了不将注解处理器的代码打包进apk. 我们需要将注解和注解处理器分开. 具体的组织如下:

  • annotations: annotations是一个java lib. 是我们自定义的注解
  • processors: processors也是一个java lib. 是我们的注解处理器
  • viewbinding: 为提供为app的api.

annotations

首先我们在annotation模块定义一个注解

@target(elementtype.field)
@retention(retentionpolicy.source)
public @interface bindview {
    int value() default -1;
}

processors

在讲处理器模块前, 我们先看看期望生成的代码模板:

public class mainactivity$viewbinding {
  public mainactivity$viewbinding(mainactivity activity, view view) {
    if (activity == null) {
      return;
    }
    activity.mtvtextview = view.findviewbyid(2131165249);
  }
}

生成的代码的类名为: xxxx$viewbinding

然后在构造函数中对传入的activity中的view进行赋值.

定义处理规则.

  • bindview只能标注字段.
  • bindview不能标注接口中的字段, 只能标注类中的字段.
  • bindview不能标注抽象类中的字段.
  • bindview不能标注被private, static或者final修饰的字段
  • bindview标注字段所属的类必须是activity的子类.
  • bindview标注的字段必须是view的子类

定义好这些规则后, 我们就可以来看处理器的代码了.

处理过程

@autoservice(processor.class)
public class viewbindingprocessor extends abstractprocessor {
    private types types;
    private filer filer;
    private messager messager;
    private elements elements;
    private map<string, viewclass> map = new hashmap<>();
    private static final string type_activity = "android.app.activity";
    private static final string type_view = "android.view.view";
    @override
    public synchronized void init(processingenvironment processingenvironment) {
        super.init(processingenvironment);
        types = processingenvironment.gettypeutils();
        filer = processingenvironment.getfiler();
        messager = processingenvironment.getmessager();
        elements = processingenvironment.getelementutils();
    }
    @override
    public boolean process(set<? extends typeelement> set, roundenvironment roundenvironment) {
        map.clear(); //该方法会被调用多次, 所以每次进入时, 首先清空之前的脏数据
        lognote("start process");
        for (element e : roundenvironment.getelementsannotatedwith(bindview.class)) {
            if (!isvalid(e)) { //首先判断被标注的元素是否符合我们上面定的规则
                return true; //出现错误, 停止编译
            }
            lognote("start parse annotations");
            performparseannotations(e); //开始解析注解
        }
        lognote("start generate code");
        generatecode(); //生成代码
        return true;
    }
    private boolean isvalid(element element) {
        if (!(element instanceof variableelement)) {
            logerror("bindview只能标注字段");
            return false;
        }
        variableelement variableelement = (variableelement) element;
        typeelement typeelement = (typeelement) variableelement.getenclosingelement();
        if (typeelement.getkind() != elementkind.class) {
            logerror("只能标注类中的字段");
            return false;
        }
        if (typeelement.getmodifiers().contains(modifier.abstract)) {
            logerror("不能标注抽象类中的字段");
            return false;
        }
        for (modifier modifier : element.getmodifiers()) {
            if (modifier == modifier.private || modifier == modifier.static ||
                    modifier == modifier.final) {
                logerror("bindview不能标注被static," +
                        "private或者final的字段");
                return false;
            }
        }
        if (!issubtype(typeelement.astype(), type_activity)) { //判断被标注的字段的类是不是activity的子类
            logerror(typeelement.getsimplename() + "必须是 activity的子类");
            return false;
        }
        if (!issubtype(variableelement.astype(), type_view)) { //判断被标注的字段是不是view的子类
            logerror("bindview只能标注view的子类");
            return false;
        }
        return true;
    }
    private boolean issubtype(typemirror tm, string type) {
        boolean issubtype = false;
        while (tm != null) { //循环获取父类信息
            if (type.equals(tm.tostring())) { //通过全路径是否相等
                issubtype = true;
                break;
            }
            typeelement supertypeelem = (typeelement) types.aselement(tm);
            if (supertypeelem != null) {
                tm = supertypeelem.getsuperclass();
            } else { //如果为空, 说明没了父类, 所以直接退出
                break;
            }
        }
        return issubtype;
    }
    private void performparseannotations(element element) {
        variableelement variableelement = (variableelement) element;
        typeelement typeelement = (typeelement) variableelement.getenclosingelement();
        string classname = typeelement.getsimplename().tostring();
        viewclass viewclass = map.get(classname);
        viewfield field = new viewfield(variableelement);
        if (viewclass == null) {
            viewclass = new viewclass(elements.getpackageof(variableelement).getqualifiedname().tostring(),
                    classname, typeelement);
            map.put(classname, viewclass);
        }
        viewclass.addfield(field);
    }
    private void generatecode() {
        for (viewclass vc : map.values()) {
            try {
                vc.generatecode().writeto(filer);
            } catch (ioexception e) {
                e.printstacktrace();
                logerror("error in parse");
            }
        }
    }
    @override
    public sourceversion getsupportedsourceversion() {
        return sourceversion.latestsupported();
    }
    @override
    public set<string> getsupportedannotationtypes() {
        set<string> annotations = new linkedhashset<>();
        annotations.add(bindview.class.getcanonicalname());
        return annotations;
    }
    private void logerror(string msg) {
        log(diagnostic.kind.error, msg);
    }
    private void lognote(string msg) {
        log(diagnostic.kind.note, msg);
    }
    private void log(diagnostic.kind kind, string msg) {
        messager.printmessage(kind, msg);
    }
}

为了使代码结构更为清晰, 这里将注解标注的字段的信息抽象为viewfield类, 字段所属的类的信息抽象为viewclass.

public class viewfield {
    private string fieldname;
    private int id;
    public viewfield(variableelement variableelement) {
        id = variableelement.getannotation(bindview.class).value();
        fieldname = variableelement.getsimplename().tostring();
    }
    public string getfieldname() {
        return fieldname;
    }
    public int getid() {
        return id;
    }
}
public class viewclass {
    private string packname;
    private string classname;
    private list<viewfield> fields = new arraylist<>();
    private typeelement typeelement;
    public viewclass(string packname, string classname, typeelement typeelement) {
        this.packname = packname;
        this.classname = classname;
        this.typeelement = typeelement;
    }
    public void addfield(viewfield viewfield) {
        fields.add(viewfield);
    }
    public javafile generatecode() { //为了方便, 这里生成代码用了javapoet库来生成代码
        methodspec.builder con = methodspec.constructorbuilder()
                .addmodifiers(modifier.public)
                .addparameter(typename.get(typeelement.astype()), "activity")
                .addparameter(classname.get("android.view", "view"), "view")
                .begincontrolflow("if (activity == null)")
                .addstatement("return")
                .endcontrolflow();
        for (viewfield f : fields) {
            con.addstatement("activity.$n = view.findviewbyid($l)", f.getfieldname(), f.getid());
        }
        fieldspec.builder fid = fieldspec.builder(typename.get(typeelement.astype()), "activity");
        typespec typespec = typespec.classbuilder(classname + "$viewbinding")
                .addmodifiers(modifier.public)
                .addfield(fid.build())
                .addmethod(con.build())
                .build();
        return javafile.builder(packname, typespec).build();
    }
}

处理过程其实并不复杂, 只是需要我们熟悉api而已, 因此, 接下来总结一下获取一些常用信息的方法:

常用的api

public class viewbindingprocessor extends abstractprocessor {
    private types types;
    private filer filer;
    private messager messager;
    private elements elements;
    private static final string type_activity = "android.app.activity";
    private static final string type_view = "android.view.view";
    @override
    public synchronized void init(processingenvironment processingenvironment) {
        super.init(processingenvironment);
        types = processingenvironment.gettypeutils();
        filer = processingenvironment.getfiler();
        messager = processingenvironment.getmessager();
        elements = processingenvironment.getelementutils();
    }
    @override
    public boolean process(set<? extends typeelement> set, roundenvironment roundenvironment) {
        for (element e : roundenvironment.getelementsannotatedwith(bindview.class)) {
            string packname = elements.getpackageof(e).getqualifiedname().tostring(); //获取包名
            //2: 获取类名.
            //如果标注的是类的话
            typeelement t = (typeelement)e;
            string classname = t.getsimplename().tostring();
            //如果被标注的是字段或者是方法
            typeelement t = (typeelement)e.getenclosingelement();
            string classname = t.getsimplename().tostring();
            //3. 获取方法名字, 或者字段名字
            string name = e.getsimplename().tostring();
            //4: 获取标注的注解
            bindview annotation = e.getannotation(bindview.class);
            int id = annotation.value();
            //5: 判断被标注的元素类型, 以字段类型为例子
            elementkind kind = e.getkind();
            if (kind == elementkind.field) {
            }
            //6: 获取元素的修饰符. 我们以被修饰的字段为例子.
            for (modifier modifier : e.getmodifiers()) {
                if (modifier == modifier.private || modifier == modifier.static ||
                modifier == modifier.final) {
                  logerror("bindview不能标注被static," +
                    "private或者final的字段");
                }
            }
            //7: 判读被标注的元素的是不是某个类的子类, 以view类为例子, 判读被修饰的字段是否是view的子类
            typemirror tm = e.astype();
            boolean issubtype = false;
            while (tm != null) {
                if ("android.view.view".equals(tm.tostring())) {
                    issubtype = true;
                    break;
                }
                typeelement t = (typeelement)types.aselement(tm);
                if (t != null) {
                    tm = t.getsuperclass(); //获取父类信息
                } else {
                    //如果为空, 说明没了父类, 所以直接退出
                    break;
                }
            }
        }
        return true;
    }
}

viewbinding

模板代码已经生成了, 但是我们还需要实例化这些类. 这个工作交由viewbinding. 它提供一些绑定的api给app. 这样我们就不需要手动调用了.

实现的思路: 运行时利用反射去实例化对应的模板类. 为了降低反射的消耗, 内部会做响应的缓存操作.

public class viewbinding {
    private static string latter_name = "$viewbinding";
    private static map<class<?>, constructor<?>> cache = new hashmap<>();
    public static <t extends activity> void bind(t target) {
        view sourceview = target.getwindow().getdecorview();
        bind(target, sourceview);
    }
     public static <t> void bind(t target, view sourceview) {
        class<? extends activity> cl = target.getclass();
        try {
            class<?> bindclass = findbindclass(cl);
            constructor<?> constructor = findbindconstructor(bindclass, cl);
            constructor.newinstance(target, sourceview);
        } catch (classnotfoundexception e) {
            e.printstacktrace();
        } catch (nosuchmethodexception e) {
            e.printstacktrace();
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (instantiationexception e) {
            e.printstacktrace();
        } catch (invocationtargetexception e) {
            e.printstacktrace();
        }
    }
    private static class<?> findbindclass(class<?> targetclass) throws classnotfoundexception {
        return targetclass.getclassloader().loadclass(targetclass.getname() + latter_name);
    }
    private static constructor<?> findbindconstructor(class<?> bindclass, class<? extends activity> targetclass) throws nosuchmethodexception {
        constructor<?> constructor = cache.get(bindclass);
        if (constructor == null) {
            constructor = bindclass.getconstructor(targetclass, view.class);
            cache.put(bindclass, constructor);
        }
        return constructor;
    }
}

使用

注解处理器现在算是开发好了. 最后的步骤就是在app中添加依赖, 然后实现绑定.

在app的build.gradle添加下面的依赖:

implementation project(':viewbinding')
implementation project(':annotations')
annotationprocessor project(':processors')

然后在mainactivity中实现注入:

public class mainactivity extends appcompatactivity {
    @bindview(r.id.main_tv_hello)
    textview mtvtextview;
    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);
        viewbinding.bind(this);
        mtvtextview.settext("xuixi");
    }
}

完…

参考资料

  • http://jinchim.com/2017/08/23/jbind/
  • http://blog.csdn.net/dd864140130/article/details/53875814

到此这篇关于java注解处理器实战的文章就介绍到这了,更多相关java注解处理器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com