Java基礎(chǔ)(二)-注解

一、定義

Java提供的一種源程序中的元素關(guān)聯(lián)任何信息和任何元數(shù)據(jù)的途徑和方法。我把它簡單理解為一個標簽。
Java SE5.0版本引入該概念。

1.1注解語法:

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description { 
    String desc();
  
    int age() default 18;
}

1.2.類定義
使用@interface關(guān)鍵字定義注解

1.3.成員變量規(guī)范

  • 成員類型是受限的,合法類型包括:基本類型及String、Class、Annotation、Enumeration
  • 如果注解只有一個成員變量,則命名必須為value(),在使用時可直接賦值
  • 注解類可以沒有成員,沒有成員的注解稱為標識注解
  • 成員以無參無異常方式聲明
  • 可以用default為成員指定一個默認值

1.4.元注解說明

注解名 作用域 說明
@Target ElementType.ANNOTATION_TYPE 給一個注解進行注解
ElementType.CONSTRUCTOR 構(gòu)造方法
ElementType.FIELD 屬性
ElementType.LOCAL_VARIABLE 局部變量
ElementType.METHOD 方法
ElementType.PACKAGE 包
ElementType.PARAMETER 方法參數(shù)
ElementType.TYPE 類、接口、枚舉
限制的運行場景,可以多選,以”,”分隔。
@Retention RetentionPolicy.SOURCE 只在源碼顯示,編譯時丟棄
RetentionPolicy.CLASS 編譯時記錄到class中,運行時丟棄
RetentionPolicy.RUNTIME 運行時存在,可反射讀取
生命周期
@Inherited 允許子類繼承
@Documented 生成javadoc時會包含注解

二、自定義注解
2.1.運行時注解

@注解名(成員名1=“成員值1”,成員名2=“成員值2”,...)
@Description(desc = “class annotation")
public class MyClass {
}

注解解析
通過反射獲取類、函數(shù)或成員上的運行時注解信息,實現(xiàn)動態(tài)控制程序運行邏輯。

try {
    Class clz = Class.forName("XXX");
    /**
     * 獲取類上注解
     */
    //類上是否存在該注解
    boolean isExit = clz.isAnnotationPresent(Description.class);
    if (isExit) {
        //獲取注解實例
        Description desc = (Description) clz.getAnnotation(Description.class);
        System.out.println(desc.value());
    }
    /**
     * 獲取方法上注解
     */
    Method[] methods = clz.getMethods();
    for (Method method : methods) {
        boolean isMethodExit = method.isAnnotationPresent(Description.class);
        if (isMethodExit) {
            Description desc = (Description) method.getAnnotation(Description.class);
            System.out.println(desc.value());
        }
    }
    //or
    for (Method method : methods) {
        Annotation[] annotations = method.getAnnotations();
        for (Annotation ann : annotations) {
            if(ann instanceof Description){
                Description d = (Description) ann;
                System.out.println(d.value());
            }
        }
    }
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

2.2 編譯時注解
APT 在編譯期通過注解生成.java文件。
annotation:注解標記

@Retention(RetentionPolicy.CLASS)//編譯時注解
@Target(ElementType.FIELD)//注解范圍為類成員(構(gòu)造方法、方法、成員變量)
public @interface BindView {
    int value();//獲取對應(yīng)View的id
}

processor: 生成對應(yīng)的類文件

/**
 * 在使用注解處理器需要先聲明和做一系列處理生成:
 * META-INF/services/javax.annotation.processing.Processor文件
 * 而@AutoService 可以幫你干了這個事
 */
@AutoService(Processor.class)
public class BindViewProcessor extends AbstractProcessor {

    /**
     * 這里有個問題,Messager無法打印,原因未知
     */
    private Messager mMessager;
    private Elements mElementUtils;
    private Map<String, ClassCreatorProxy> mProxyMap = new HashMap<>();

    /**
     * 初始化
     *
     * @param processingEnvironment 提供很多有用的工具類Elements, Types 和 Filer
     */
    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment) {
        super.init(processingEnvironment);
        mMessager = processingEnvironment.getMessager();
        mElementUtils = processingEnvironment.getElementUtils();
    }

    /**
     * 指定這個注解處理器是注冊給哪個注解的,這里說明是注解BindView
     *
     * @return
     */
    @Override
    public Set<String> getSupportedAnnotationTypes() {
        HashSet<String> supportTypes = new LinkedHashSet<>();
        supportTypes.add(BindView.class.getCanonicalName());
        return supportTypes;
    }

    /**
     * 指定使用的Java版本,通常這里返回SourceVersion.latestSupported()
     *
     * @return
     */
    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }

    /**
     * 掃描、評估和處理注解的代碼,生成Java文件
     *
     * @param set
     * @param roundEnvironment
     * @return
     */
    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        mMessager.printMessage(Diagnostic.Kind.NOTE, "processing...");
        mProxyMap.clear();
        //得到所有注解
        Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindView.class);
        for (Element element : elements) {
            VariableElement variableElement = (VariableElement) element;
            TypeElement classElement = (TypeElement) variableElement.getEnclosingElement();
            String fullClassName = classElement.getQualifiedName().toString();
            ClassCreatorProxy proxy = mProxyMap.get(fullClassName);
            if (proxy == null) {
                proxy = new ClassCreatorProxy(mElementUtils, classElement);
                mProxyMap.put(fullClassName, proxy);
            }
            BindView bindAnnotation = variableElement.getAnnotation(BindView.class);
            int id = bindAnnotation.value();
            proxy.putElement(id, variableElement);
        }

        //通過遍歷mProxyMap,創(chuàng)建java文件
        for (String key : mProxyMap.keySet()) {
            ClassCreatorProxy proxyInfo = mProxyMap.get(key);
            try {
                mMessager.printMessage(Diagnostic.Kind.NOTE, " --> create " + proxyInfo.getProxyClassFullName());
                JavaFileObject jfo = processingEnv.getFiler().createSourceFile(proxyInfo.getProxyClassFullName(), proxyInfo.getTypeElement());
                Writer writer = jfo.openWriter();
                writer.write(proxyInfo.generateJavaCode());
                writer.flush();
                writer.close();
            } catch (IOException e) {
                mMessager.printMessage(Diagnostic.Kind.NOTE, " --> create " + proxyInfo.getProxyClassFullName() + "error");
            }
        }

        mMessager.printMessage(Diagnostic.Kind.NOTE, "process finish ...");
        return true;
    }
}

public class ClassCreatorProxy {
    private String mBindingClassName;
    private String mPackageName;
    private TypeElement mTypeElement;
    private Map<Integer, VariableElement> mVariableElementMap = new HashMap<>();

    public ClassCreatorProxy(Elements elementUtils, TypeElement classElement) {
        this.mTypeElement = classElement;
        PackageElement packageElement = elementUtils.getPackageOf(mTypeElement);
        String packageName = packageElement.getQualifiedName().toString();
        String className = mTypeElement.getSimpleName().toString();
        this.mPackageName = packageName;
        this.mBindingClassName = className + "_ViewBinding";
    }

    public void putElement(int id, VariableElement element) {
        mVariableElementMap.put(id, element);
    }

    /**
     * 創(chuàng)建Java代碼
     *
     * @return
     */
    public String generateJavaCode() {
        StringBuilder builder = new StringBuilder();
        builder.append("package ").append(mPackageName).append(";\n\n");
        builder.append('\n');
        builder.append("public class ").append(mBindingClassName);
        builder.append(" {\n");

        generateMethods(builder);

        builder.append('\n');
        builder.append("}\n");
        return builder.toString();
    }

    /**
     * 創(chuàng)建Java代碼
     *
     * javapoet
     */
    public TypeSpec generateJavaCode2() {
        TypeSpec bindingClass = TypeSpec.classBuilder(mBindingClassName)
                .addModifiers(Modifier.PUBLIC)
                .addMethod(generateMethods2())
                .build();
        return bindingClass;

    }

    /**
     * 拼接對應(yīng)方法
     *
     * @param builder
     */
    private void generateMethods(StringBuilder builder) {
        builder.append("public void bind(" + mTypeElement.getQualifiedName() + " host ) {\n");
        for (int id : mVariableElementMap.keySet()) {
            VariableElement element = mVariableElementMap.get(id);
            String name = element.getSimpleName().toString();
            String type = element.asType().toString();
            builder.append("host." + name).append(" = ");
            builder.append("(" + type + ")(((android.app.Activity)host).findViewById( " + id + "));\n");
        }
        builder.append("  }\n");
    }

    /**
     * 拼接對應(yīng)方法
     *
     *  javapoet
     */
    private MethodSpec generateMethods2() {
        ClassName host = ClassName.bestGuess(mTypeElement.getQualifiedName().toString());
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("bind")
                .addModifiers(Modifier.PUBLIC)
                .returns(void.class)
                .addParameter(host, "host");

        for (int id : mVariableElementMap.keySet()) {
            VariableElement element = mVariableElementMap.get(id);
            String name = element.getSimpleName().toString();
            String type = element.asType().toString();
            methodBuilder.addCode("host." + name + " = " + "(" + type + ")(((android.app.Activity)host).findViewById( " + id + "));");
        }
        return methodBuilder.build();
    }

    public String getProxyClassFullName() {
        return mPackageName + "." + mBindingClassName;
    }

    public TypeElement getTypeElement() {
        return mTypeElement;
    }
}

gradle配置:

autoSerive :
   gradle 4.4 + 3.1.0
    implementation 'com.google.auto.service:auto-service:1.0-rc6'
    gradle 5.0+版本:
    api 'com.google.auto.service:auto-service:1.0-rc6'
    annotationProcessor 'com.google.auto.service:auto-service:1.0-rc6'

javapoet:
   implementation 'com.squareup:javapoet:1.10.0'

library 通過反射使用processor創(chuàng)建出來的類:

public class BindViewTools {
    public static void bind(Activity activity) {

        Class clazz = activity.getClass();
        try {
            Class bindViewClass = Class.forName(clazz.getName() + "_ViewBinding");
            Method method = bindViewClass.getMethod("bind", activity.getClass());
            method.invoke(bindViewClass.newInstance(), activity);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

使用:

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.txt)
    TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BindViewTools.bind(this);
        mTextView.setText("annotation apt");
    }
}

@AutoService(Processor.class) 注解處理器聲明。
AbstractProcessor 掃描、評估和處理注解的代碼,生成Java文件。
javapoet 替代StringBuilder的append的一種更優(yōu)雅的寫法工具。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

  • 什么是注解(Annotation):Annotation(注解)就是Java提供了一種元程序中的元素關(guān)聯(lián)任何信息和...
    九尾喵的薛定諤閱讀 3,425評論 0 2
  • 前言 現(xiàn)在在我們構(gòu)建自己或公司的項目中,或多或少都會依賴幾個流行比較屌的第三方庫,比如:Butter Knife、...
    戴定康閱讀 4,046評論 0 17
  • 一、概念 ??Annotation(注解)就是Java提供了一種源程序中的元素關(guān)聯(lián)任何信息和任何元數(shù)據(jù)(metad...
    從菜鳥到老菜鳥閱讀 2,259評論 0 2
  • 從JDK5開始,Java增加了Annotation(注解),Annotation是代碼里的特殊標記,這些標記可以在...
    CarlosLynn閱讀 658評論 0 2
  • 備注: 本文大部分內(nèi)容及代碼均來自網(wǎng)上,具體引用看末尾 8.參考引用** 概念及作用 JDK注解 元注解 自定...
    ting723閱讀 1,588評論 2 5

友情鏈接更多精彩內(nèi)容