AOP概念
AOP為Aspect Oriented Programming的縮寫,意為:面向切面編程,通過預(yù)編譯方式和運(yùn)行期動(dòng)態(tài)代理實(shí)現(xiàn)程序功能的統(tǒng)一維護(hù)的一種技術(shù)虐沥。AOP是OOP的延續(xù),是軟件開發(fā)中的一個(gè)熱點(diǎn),也是Spring框架中的一個(gè)重要內(nèi)容冀痕,是函數(shù)式編程的一種衍生范型。利用AOP可以對(duì)業(yè)務(wù)邏輯的各個(gè)部分進(jìn)行隔離狸演,從而使得業(yè)務(wù)邏輯各部分之間的耦合度降低金度,提高程序的可重用性,同時(shí)提高了開發(fā)的效率严沥。
Android AOP三劍客: APT, AspectJ, Javassist
傳送門:android-aop-samples
工程目錄結(jié)構(gòu)
.
- annotation 定義注解
- apt-library apt輔助工具類
- apt-processor 自定義注解解析器猜极,生成輔助代碼
- apt-plugin 自定義Gradle插件,實(shí)現(xiàn)切面和操作字節(jié)碼的插件
- app 主目錄
Android APT
APT(Annotation Processing Tool 的簡稱)消玄,可以在代碼編譯期解析注解跟伏,并且生成新的 Java 文件,減少手動(dòng)的代碼輸入◆婀希現(xiàn)在有很多主流庫都用上了 APT受扳,比如 Dagger2, ButterKnife, EventBus3 等
定義注解
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface BindView {
int value();
}
創(chuàng)建一個(gè)Module,自定義AbstractProcessor兔跌,并且用@AutoService標(biāo)記
- AutoService會(huì)自動(dòng)在META-INF文件夾下生成Processor配置信息文件勘高,該文件里就是實(shí)現(xiàn)該服務(wù)接口的具體實(shí)現(xiàn)類。而當(dāng)外部程序裝配這個(gè)模塊的時(shí)候坟桅,
就能通過該jar包META-INF/services/里的配置文件找到具體的實(shí)現(xiàn)類名华望,并裝載實(shí)例化,完成模塊的注入
@AutoService(Processor.class)
public class BindViewProcessor extends AbstractProcessor {
private Messager mMessager;
private Elements mElementUtils;
private Map<String, ClassFactory> mProxyMap = new HashMap<>();
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
mMessager = processingEnv.getMessager();
mElementUtils = processingEnv.getElementUtils();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
HashSet<String> supportTypes = new LinkedHashSet<>();
supportTypes.add(BindView.class.getCanonicalName());
return supportTypes;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@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();
//elements的信息保存到mProxyMap中
ClassFactory proxy = mProxyMap.get(fullClassName);
if (proxy == null) {
proxy = new ClassFactory(mElementUtils, classElement);
mProxyMap.put(fullClassName, proxy);
}
BindView bindAnnotation = variableElement.getAnnotation(BindView.class);
int id = bindAnnotation.value();
proxy.putElement(id, variableElement);
}
//通過javapoet生成
for (String key : mProxyMap.keySet()) {
ClassFactory proxyInfo = mProxyMap.get(key);
JavaFile javaFile = JavaFile.builder(proxyInfo.getPackageName(), proxyInfo.generateJavaCode()).build();
try {
// 生成文件
javaFile.writeTo(processingEnv.getFiler());
} catch (IOException e) {
e.printStackTrace();
}
}
mMessager.printMessage(Diagnostic.Kind.NOTE, "process finish ...");
return true;
}
}
process方法仅乓,處理我們自定義的注解赖舟,生成代碼,這里使用的squareup公司的javapoet庫輔助生成代碼
public class ClassFactory {
private String mBindingClassName;
private String mPackageName;
private TypeElement mTypeElement;
private Map<Integer, VariableElement> mVariableElementMap = new HashMap<>();
public ClassFactory(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);
}
public TypeSpec generateJavaCode() {
TypeSpec bindingClass = TypeSpec.classBuilder(mBindingClassName)
.addModifiers(Modifier.PUBLIC)
.addMethod(generateMethods())
.build();
return bindingClass;
}
private MethodSpec generateMethods() {
ClassName activity = ClassName.bestGuess(mTypeElement.getQualifiedName().toString());
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("bind")
.addModifiers(Modifier.PUBLIC)
.returns(void.class)
.addParameter(activity, "activity");
for (int id : mVariableElementMap.keySet()) {
VariableElement element = mVariableElementMap.get(id);
String name = element.getSimpleName().toString();
String type = element.asType().toString();
methodBuilder.addCode("activity." + name + " = " + "(" + type + ")(((android.app.Activity)activity).findViewById( " + id + "));\n\n");
}
return methodBuilder.build();
}
public String getPackageName() {
return mPackageName;
}
}
generateMethods方法通過for循環(huán)構(gòu)建代碼夸楣,findViewById綁定view
我們先看下原本的MainActivity有什么東東
public class MainActivity extends AppCompatActivity {
@BindView(R.id.button)
Button button;
@BindView(R.id.tv)
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BindViewTools.bind(this);
textView.setText("bind Button success");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doMarkDown();
}
});
}
}
這個(gè)BindViewTools.bind(this)傳送門進(jìn)去看看
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();
}
}
}
我們可以看到他是通過反射尋找的是MainActivity_ViewBinding的類宾抓,并進(jìn)行Id綁定的
可以在build/intermediates/classes/debug/包名/MainActivity_ViewBinding.class看到生成的代碼
這下就很清晰了
1.首先定義注解
2.BindViewProcessor里的process 解析注解,生成輔助類MainActivity_ViewBinding
3.在入口BindViewTools.bind(this)豫喧,反射找到生成的MainActivity_ViewBinding類并進(jìn)行findViewById石洗。
總結(jié)
本章節(jié)主要說了APT的簡單使用,從使用角度來說紧显,APT技術(shù)并沒有難度讲衫,重點(diǎn)是怎么設(shè)計(jì),在實(shí)際項(xiàng)目中可以把很多繁瑣重復(fù)性的工作鸟妙,通過APT來生成各種代碼.