赞
踩
上篇博客中无法对构造方法应用AOP,本篇做了修改
项目目录:
没有给出的类,在上篇博客中:
依赖库中的build.gradle文件
- apply plugin: 'com.android.library'
-
- import com.android.build.gradle.LibraryPlugin
- import org.aspectj.bridge.IMessage
- import org.aspectj.bridge.MessageHandler
- import org.aspectj.tools.ajc.Main
-
- buildscript {
- repositories {
- mavenCentral()
- }
- dependencies {
- classpath 'org.aspectj:aspectjtools:1.8.9'
- classpath 'org.aspectj:aspectjweaver:1.8.9'
- }
- }
-
- android {
- compileSdkVersion 25
- buildToolsVersion "25.0.2"
- lintOptions {
- abortOnError false
- }
-
- defaultConfig {
- minSdkVersion 15
- targetSdkVersion 25
- versionCode 1
- versionName "1.0"
-
- testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
-
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- }
-
-
- android.libraryVariants.all { variant ->
- LibraryPlugin plugin = project.plugins.getPlugin(LibraryPlugin)
- JavaCompile javaCompile = variant.javaCompile
- javaCompile.doLast {
- String[] args = ["-showWeaveInfo",
- "-1.5",
- "-inpath", javaCompile.destinationDir.toString(),
- "-aspectpath", javaCompile.classpath.asPath,
- "-d", javaCompile.destinationDir.toString(),
- "-classpath", javaCompile.classpath.asPath,
- "-bootclasspath", plugin.project.android.bootClasspath.join(
- File.pathSeparator)]
-
- MessageHandler handler = new MessageHandler(true);
- new Main().run(args, handler)
-
- def log = project.logger
- for (IMessage message : handler.getMessages(null, true)) {
- switch (message.getKind()) {
- case IMessage.ABORT:
- case IMessage.ERROR:
- case IMessage.FAIL:
- log.error message.message, message.thrown
- break;
- case IMessage.WARNING:
- case IMessage.INFO:
- log.info message.message, message.thrown
- break;
- case IMessage.DEBUG:
- log.debug message.message, message.thrown
- break;
- }
- }
- }
- }
-
- dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
- androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
- exclude group: 'com.android.support', module: 'support-annotations'
- })
- compile 'com.android.support:appcompat-v7:25.1.0'
- testCompile 'junit:junit:4.12'
- }
主工程build.gradle文件
- apply plugin: 'com.android.application'
-
- import org.aspectj.bridge.IMessage
- import org.aspectj.bridge.MessageHandler
- import org.aspectj.tools.ajc.Main
- buildscript {
- repositories {
- mavenCentral()
- }
- dependencies {
- classpath 'org.aspectj:aspectjtools:1.8.9'
- classpath 'org.aspectj:aspectjweaver:1.8.9'
- }
- }
- android {
- compileSdkVersion 25
- buildToolsVersion "25.0.2"
- defaultConfig {
- applicationId "cn.edu.sxu.www.aopdemolibrary"
- minSdkVersion 15
- targetSdkVersion 25
- versionCode 1
- versionName "1.0"
- testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- }
-
- final def log = project.logger
- final def variants = project.android.applicationVariants
-
- variants.all { variant ->
- if (!variant.buildType.isDebuggable()) {
- log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")
- return;
- }
-
- JavaCompile javaCompile = variant.javaCompile
- javaCompile.doLast {
- String[] args = ["-showWeaveInfo",
- "-1.8",
- "-inpath", javaCompile.destinationDir.toString(),
- "-aspectpath", javaCompile.classpath.asPath,
- "-d", javaCompile.destinationDir.toString(),
- "-classpath", javaCompile.classpath.asPath,
- "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]
- log.debug "ajc args: " + Arrays.toString(args)
-
- MessageHandler handler = new MessageHandler(true);
- new Main().run(args, handler);
- for (IMessage message : handler.getMessages(null, true)) {
- switch (message.getKind()) {
- case IMessage.ABORT:
- case IMessage.ERROR:
- case IMessage.FAIL:
- log.error message.message, message.thrown
- break;
- case IMessage.WARNING:
- log.warn message.message, message.thrown
- break;
- case IMessage.INFO:
- log.info message.message, message.thrown
- break;
- case IMessage.DEBUG:
- log.debug message.message, message.thrown
- break;
- }
- }
- }
- }
-
- dependencies {
- compile fileTree(include: ['*.jar'], dir: 'libs')
- androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
- exclude group: 'com.android.support', module: 'support-annotations'
- })
- compile 'com.android.support:appcompat-v7:25.1.0'
- testCompile 'junit:junit:4.12'
- compile project(':aoplibrary')
- }
- package cn.edu.sxu.www.aoplibrary;
-
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.Around;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Pointcut;
- import org.aspectj.lang.reflect.CodeSignature;
- import org.aspectj.lang.reflect.ConstructorSignature;
- import org.aspectj.lang.reflect.MethodSignature;
-
- /**
- * Aspect representing the cross cutting-concern: Method and Constructor Tracing.
- */
- @Aspect
- public class TraceAspect {
-
- private static final String POINTCUT_METHOD =
- "execution(@cn.edu.sxu.www.aoplibrary.DebugTrace * *(..))";
-
- private static final String POINTCUT_CONSTRUCTOR =
- "execution(@cn.edu.sxu.www.aoplibrary.DebugTrace *.new(..))";
-
- @Pointcut(POINTCUT_METHOD)
- public void methodAnnotatedWithDebugTrace() {}
-
- @Pointcut(POINTCUT_CONSTRUCTOR)
- public void constructorAnnotatedDebugTrace() {}
-
- @Around("methodAnnotatedWithDebugTrace() || constructorAnnotatedDebugTrace()")
- public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
-
- CodeSignature methodSignature=null;
- if(joinPoint.getSignature() instanceof MethodSignature)//普通方法
- {
- methodSignature = (MethodSignature) joinPoint.getSignature();
- }
- else if(joinPoint.getSignature() instanceof ConstructorSignature)//构造方法
- {
- methodSignature = (ConstructorSignature) joinPoint.getSignature();
- }
-
- String className = methodSignature.getDeclaringType().getSimpleName();
- String methodName = methodSignature.getName();
-
- final StopWatch stopWatch = new StopWatch();
- stopWatch.start();
- Object result = joinPoint.proceed();
- stopWatch.stop();
-
- DebugLog.log(className, buildLogMessage(methodName, stopWatch.getTotalTimeMillis()));
-
- return result;
- }
-
- /**
- * Create a log message.
- *
- * @param methodName A string with the method name.
- * @param methodDuration Duration of the method in milliseconds.
- * @return A string representing message.
- */
- private static String buildLogMessage(String methodName, long methodDuration) {
- StringBuilder message = new StringBuilder();
- message.append("Gintonic --> ");
- message.append(methodName);
- message.append(" --> ");
- message.append("[");
- message.append(methodDuration);
- message.append("ms");
- message.append("]");
-
- return message.toString();
- }
- }
- package cn.edu.sxu.www.aopdemolibrary;
-
- import android.os.Bundle;
- import android.os.SystemClock;
- import android.support.v7.app.AppCompatActivity;
- import android.view.View;
- import android.widget.Button;
-
- import cn.edu.sxu.www.aoplibrary.DebugLog;
- import cn.edu.sxu.www.aoplibrary.DebugTrace;
- import cn.edu.sxu.www.aoplibrary.StopWatch;
-
- public class MainActivity extends AppCompatActivity implements View.OnClickListener{
-
- private Button button;
- private Button button2;
- private Button button3;
- private String TAG="cn.edu.sxu.www.aopdemo.MainActivity";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- button= (Button) findViewById(R.id.button);
- button2= (Button) findViewById(R.id.button2);
- button3= (Button) findViewById(R.id.button3);
- button.setOnClickListener(this);
- button2.setOnClickListener(this);
- button3.setOnClickListener(this);
- }
-
- @Override
- public void onClick(View view) {
-
- switch (view.getId())
- {
- case R.id.button:
- commonTest();
- break;
- case R.id.button2:
- aopTest();
- break;
- case R.id.button3:
- initConstructor();
- break;
- }
-
- }
-
- /**
- * 普通统计
- */
-
- private void commonTest()
- {
- final StopWatch stopWatch = new StopWatch();
- stopWatch.start();
- SystemClock.sleep(2000);
- stopWatch.stop();
-
- DebugLog.log(TAG, "所用时长:"+stopWatch.getTotalTimeMillis());
-
- }
-
- /**
- * aop 统计
- */
- @DebugTrace
- private void aopTest()
- {
- SystemClock.sleep(3000);
- }
-
- /**
- * 演示构造方法
- */
- private void initConstructor()
- {
-
- // Person person=new Person("张三",10);
- // person.setAge(80);
- Person person=new Person();
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/activity_main"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="官网demo,统计方法运行时间"
- android:id="@+id/textView" />
-
- <Button
- android:text="普通方式"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/textView"
- android:layout_alignParentLeft="true"
- android:layout_alignParentStart="true"
- android:layout_marginTop="42dp"
- android:id="@+id/button" />
-
- <Button
- android:text="aop方式"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/button"
- android:layout_alignRight="@+id/button"
- android:layout_alignEnd="@+id/button"
- android:layout_marginTop="87dp"
- android:id="@+id/button2" />
-
- <Button
- android:text="aop构造方法"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginBottom="69dp"
- android:id="@+id/button3"
- android:layout_alignParentBottom="true"
- android:layout_alignParentLeft="true"
- android:layout_alignParentStart="true" />
- </RelativeLayout>
- package cn.edu.sxu.www.aopdemolibrary;
-
- import android.os.SystemClock;
-
- import java.io.Serializable;
-
- import cn.edu.sxu.www.aoplibrary.DebugTrace;
-
- /**
- * Created by ${huozhenpeng} on 17/2/23.
- * Company : www.miduo.com
- * 演示AOP对构造方法的使用
- */
-
- public class Person implements Serializable {
-
-
- private String name;
- private int age;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- @DebugTrace
- public void setAge(int age) {
- this.age = age;
- SystemClock.sleep(100);
- }
-
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- SystemClock.sleep(1000);
- }
- @DebugTrace
- public Person() {
-
- SystemClock.sleep(1500);
- }
- }
源码地址:http://download.csdn.net/detail/huohacker/9761903
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。