【Android】注解框架(四)-- 一行代碼注入微信支付

目錄

  1. 【Android】注解框架(一)-- 基礎(chǔ)知識(shí)Java 反射
  2. 【Android】注解框架(二)-- 基礎(chǔ)知識(shí)(Java注解)& 運(yùn)行時(shí)注解框架
  3. 【Android】注解框架(三)-- 編譯時(shí)注解,手寫B(tài)utterKnife
  4. 【Android】注解框架(四)-- 一行代碼注入微信支付

微信一般處理方式

通常情況下當(dāng)我們接入微信的時(shí)候,微信會(huì)蛋疼的讓我們?cè)谖覀兊陌虑秩胧降奶砑?code>wxapi包,在這個(gè)包下面處理支付的相關(guān)業(yè)務(wù)邏輯。

image

這個(gè)樣子就非常蛋疼了,不談看著難受,就連我們自己的項(xiàng)目規(guī)則都被他給打亂了,那么有什么好的辦法來(lái)解決這個(gè)問題呢?

其實(shí)用我們上次學(xué)到的AnnotationProcessor就可以解決這個(gè)問題。

我們通過apt來(lái)自動(dòng)生成包名.wxapi.WXPAYEntryActivity并讓這個(gè)文件繼承我們自己寫的WXPayActivity,我們?cè)?code>WXPayActivity中來(lái)處理微信支付的邏輯,這樣WXPayActivity就可以寫在我們自己定義的模塊下面了,不僅僅局限于app,組件化的module中都可以寫,當(dāng)我們需要接入的時(shí)候直接飲用module并直接自動(dòng)生成包名.wxapi.WXPAYEntryActivity就可以了。

實(shí)現(xiàn)

首先我們看下架構(gòu)圖,大概就是下面這個(gè)樣子:

image
  1. 生成各個(gè)module

    app - 主項(xiàng)目
    wx_pay - android lib
    wx_annotaion - java lib
    wx_compiler - java lib
    
  2. wx_annotaion

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.CLASS)
    public @interface WXPayEntry {
    
        // 包名
        String packageName();
    
        // 類名
        Class<?> entryClass();
    }
    
  3. wx_pay

    這邊寫我們自己的微信支付相關(guān)的代碼

    public class WXPayActivity extends AppCompatActivity implements IWXAPIEventHandler {
        @Override
        public void onReq(BaseReq baseReq) {
    
        }
    
        @Override
        public void onResp(BaseResp baseResp) {
    
        }
    }
    
  4. wx_compiler

    java api : http://www.yq1012.com/api/index.html-overview-summary.html

    visitor不懂的自定查看:javax.lang.model.util.SimpleAnnotationValueVisitor6

    // WXEntryProcessor.class
    @AutoService(Processor.class)
    public class WXEntryProcessor extends AbstractProcessor {
    
        private Filer filer;
    
        @Override
        public synchronized void init(ProcessingEnvironment processingEnvironment) {
            super.init(processingEnvironment);
            filer = processingEnvironment.getFiler();
        }
    
        @Override
        public Set<String> getSupportedAnnotationTypes() {
            Set<String> types = new LinkedHashSet<>();
            Set<Class<? extends Annotation>> supportedAnnotations = getSupportedAnnotations();
            for (Class<? extends Annotation> supportedAnnotation : supportedAnnotations) {
                types.add(supportedAnnotation.getCanonicalName());
            }
            return types;
        }
    
        private Set<Class<? extends Annotation>> getSupportedAnnotations() {
            Set<Class<? extends Annotation>> annotations = new LinkedHashSet<>();
            annotations.add(WXPayEntry.class);
            return annotations;
        }
    
        @Override
        public SourceVersion getSupportedSourceVersion() {
            return SourceVersion.latestSupported();
        }
    
        @Override
        public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
            generateWXPayCode(roundEnvironment);
    
            return false;
        }
    
        private void generateWXPayCode(RoundEnvironment roundEnvironment) {
            WXPayEntryVisitor visitor = new WXPayEntryVisitor();
            visitor.setFiler(filer);
            scan(visitor, roundEnvironment, WXPayEntry.class);
        }
    
        private void scan(WXPayEntryVisitor visitor,
                          RoundEnvironment roundEnvironment,
                          Class<? extends Annotation> annotation) {
    
            Set<? extends Element> elementsAnnotatedWith = roundEnvironment.getElementsAnnotatedWith(annotation);
            for (Element element : elementsAnnotatedWith) {
                List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
                for (AnnotationMirror annotationMirror : annotationMirrors) {
                    Map<? extends ExecutableElement, ? extends AnnotationValue>
                            elementValues = annotationMirror.getElementValues();
    
                    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : elementValues.entrySet()) {
                        entry.getValue().accept(visitor, null);
                    }
                }
            }
    
        }
    }
    
    // WXPayEntryVisitor
    public class WXPayEntryVisitor extends SimpleAnnotationValueVisitor7<Void, Void> {
    
        private String packageName;
        private TypeMirror typeMirror;
        private Filer filer;
    
        public WXPayEntryVisitor setFiler(Filer filer) {
            this.filer = filer;
            return this;
        }
    
        @Override
        public Void visitString(String s, Void aVoid) {
            this.packageName = s;
            return aVoid;
        }
    
        @Override
        public Void visitType(TypeMirror typeMirror, Void aVoid) {
            this.typeMirror = typeMirror;
            generateWXPayCode();
            return aVoid;
        }
    
        private void generateWXPayCode() {
            // Class xxx.wxapi.WXPayEntryActivity extends WXPayActivity
            TypeSpec.Builder classSpecBuilder = TypeSpec.classBuilder("WXPayEntryActivity")
                    .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                    .superclass(TypeName.get(typeMirror));
    
            try {
                JavaFile.builder(packageName + ".wxpai", classSpecBuilder.build())
                        .build().writeTo(filer);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e);
            }
        }
    }
    
  5. 使用

    在baseApplication中使用注解

    @WXPayEntry(packageName = "com.fastaoe.wxannotationprocessordemo", 
        entryClass = WXPayActivity.class)
    public class BaseApplication extends Application {
    }
    

    此時(shí)重新build我們的工程就生成了符合要求的WXPayEntryActivity

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

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

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