Android注解处理器(APT)简单实例

参考:https://www.jianshu.com/p/07ef8ba80562

实例代码Github

新建一个名为"a_compiler"的Java Library,并添加注解Route和注解处理器RouteProcessor,在build.gradle中添加AutoService依赖库。如下图:
Android注解处理器(APT)简单实例_第1张图片

将a_compiler作为依赖添加到app中,在app的build.gradle中添加如下:

    annotationProcessor project(path: ':a_compiler')
    implementation project(path: ':a_compiler')

Route:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//添加元注解
// @Target(ElementType.TYPE)   //接口、类、枚举、注解
@Target(ElementType.TYPE)
//注解的生命周期
//RetentionPolicy.CLASS   编译阶段
@Retention(RetentionPolicy.CLASS)
public @interface Route {
     
    /**
     *路由的路径,标识一个路由节点
     */
    String path();
    /**
     * 将路由节点进行分组,可以实现按组动态加载
     */
    String group() default "";
}

RouteProcessor:

import com.google.auto.service.AutoService;
import com.hongx.compiler.annotation.Route;
import java.io.IOException;
import java.io.Writer;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
/**
 * @author: fuchenming
 * @create: 2019-08-20 08:28
 */
//@SupportedAnnotationTypes({"com.hongx.compiler.annotation.Route"})
@SupportedSourceVersion(SourceVersion.RELEASE_7)
@AutoService(Processor.class)
public class RouteProcessor extends AbstractProcessor {
     
    private Filer mFiler;
    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment) {
     
        super.init(processingEnvironment);
        mFiler = processingEnv.getFiler();
    }
//    @Override
//    public SourceVersion getSupportedSourceVersion() {
     
//        return SourceVersion.RELEASE_7;
//    }
    @Override
    public Set<String> getSupportedAnnotationTypes() {
     
        //支持的注解
        Set<String> annotations = new LinkedHashSet<>();
        annotations.add(Route.class.getCanonicalName());
//        annotations.add("com.hongx.compiler.annotation.Route");
        return annotations;
    }
    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
     
        Set<? extends Element> routeElements = roundEnvironment.getElementsAnnotatedWith(Route.class);
        // 遍历所有被注解了@Factory的元素
        for (Element element : routeElements) {
     
            Route route = element.getAnnotation(Route.class);
            String path = route.path();
            String group = route.group();
            String newClassName = path + "$$Hx";
            StringBuilder builder = new StringBuilder()
                    .append("package com.hongx.processor.auto;\n\n")
                    .append("public class ")
                    .append(newClassName)
                    .append(" {\n\n") // open class
                    .append("\tpublic String getMessage() {\n") // open method
                    .append("\t\treturn \"");
            builder.append(path).append(group).append(" !\\n");
            builder.append("\";\n") // end return
                    .append("\t}\n") // close method
                    .append("}\n"); // close class
            try {
     
                JavaFileObject source = mFiler.createSourceFile("com.hongx.processor.auto."+newClassName);
                Writer writer = source.openWriter();
                writer.write(builder.toString());
                writer.flush();
                writer.close();
            } catch (IOException e) {
     
            }
        }
        return true;
    }
}

在MainActivity使用注解,如下:

@Route(path = "Main",group = "Activity")
public class MainActivity extends AppCompatActivity {
     
...
}

点击MakeProject后,查看如下图文件:
Android注解处理器(APT)简单实例_第2张图片

使用生成的Main$$Hx:

@Route(path = "Main",group = "Activity")
public class MainActivity extends AppCompatActivity {
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void changeText(View view) {
     
        Log.i("MainActivity","click");
        Main$$Hx main$$Hx = new Main$$Hx();
        ((TextView)view).setText(main$$Hx.getMessage());
    }
}

实例代码Github:https://github.com/345166018/AndroidComponent/tree/master/SimpleAnnotationProcessor

你可能感兴趣的:(#,Android,IOC和组件化,android,注解,apt,AutoService)