基于AOP的代码插桩

场景一:统计自定义方法耗时及调用次数。

方案:通过Aspect.addBefore对自定义方法进行执行前插桩记录方法调用前时间、Aspect.addAfter对自定义方法进行执行后插桩记录执行后时间,以统计方法耗时及调用次数。

核心代码:

function addTimePrinter(targetClass: Object, methodName: string, isStatic: boolean) {
  let count: number = 0
  let t1 = 0;
  let t2 = 0;
  util.Aspect.addBefore(targetClass, methodName, isStatic, () => {
    t1 = new Date().getTime();
  })
  util.Aspect.addAfter(targetClass, methodName, isStatic, (instance: Object, ret: number) => {
 
    count+=1
    t2 = new Date().getTime();
    console.log(methodName+"方法耗时为t2 - t1 = " + (t2 - t1).toString());
    console.log(methodName+"方法调用次数为count = " + count);
    return ret;
  })
}
 
function doSomeWork(time: number) {
  let start = Date.now()
  while (Date.now()-start<time){
    continue
  }
  console.log('延时 '+time+"ms");
}
 
export class Test {
  delay1000() {
    doSomeWork(1000);  // 1000ms的任务
  }
  static delay2000() {
    doSomeWork(2000);  // 1000ms的任务
  }
}
addTimePrinter(Test,'delay1000',false)
addTimePrinter(Test,'delay2000',true)

场景二:应用间跳转--获取目标应用包名。

方案:在EntryAbility的onCreate方法中对UIAbilityContext类的startAbility方法进行插桩,以获取Want参数的bundleName属性。此场景addAfter、addBefore都可完成,本例通过addAfter实现。

核心代码:

由于UIAbilityContext是系统提供的类且没有导出,无法直接import,因此可以通过EntryAbility的context成员(该成员是从UIAbility继承而来)获取UIAbilityContext类对象,然后在onCreate方法中完成插桩操作。

import { BusinessError } from '@kit.BasicServicesKit';
import { GlobalThis} from '../utils/GlobalThis'
import util from '@ohos.util';
 
let context  = GlobalThis.getInstance().getContext("context")
 
export function Jump(){
  let want: Want = {
    bundleName: 'com.example.myapplication_taskpool_settime',
    abilityName: 'EntryAbility'
  };
  try {
    context?.startAbility(want, (err: BusinessError) => {
      if (err.code) {
        // 处理业务逻辑错误
        console.error(`testtag startAbility failed, code is ${err.code}, message is ${err.message}`);
        return;
      }
      // 执行正常业务
      console.info('testtag startAbility succeed');
    });
  } catch (err) {
    // 处理入参错误异常
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error(`testtag  startAbility failed, code is ${code}, message is ${message}`);
    console.error(`testtag  startAbility failed, code is ${code}, message is ${message}`);
  }
}
 
util.Aspect.addAfter(context?.constructor, "startAbility", false, (instance: Object, ret: Object, want: Want): void => {
    console.error("testtag 获取目标包名"+want?.bundleName);
  }
);

同理,可以采用相同的方法获取来源应用包名。例:对EntryAbility的onCreate方法进行插桩,当本应用被其他应用调用触发onCreate回调,以获取Want参数的bundleName属性。此场景addAfter、addBefore都可完成,本例通过addBefore实现。

//获取来源包名
util.Aspect.addBefore(EntryAbility, "onCreate", false, (instance: EntryAbility, want: Want): void => {
  let params = want.parameters as Record<string, Object>;
  console.error('testtag 获取来源包名'+params['ohos.aafwk.param.callerBundleName']);
});

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOP(面向切面编程)是Spring框架中的一个重要模块,它提供了一种在程序运行期间动态地将代码织入到现有代码中的方式。下面是一个简单的Spring AOP代码示例: 先,定义一个接口 `UserService`,其中包含了两个方法 `addUser` 和 `deleteUser`: ```java public interface UserService { void addUser(String username); void deleteUser(String username); } ``` 然后,创建一个实现该接口的类 `UserServiceImpl`: ```java public class UserServiceImpl implements UserService { @Override public void addUser(String username) { System.out.println("添加用户:" + username); } @Override public void deleteUser(String username) { System.out.println("删除用户:" + username); } } ``` 接下来,创建一个切面类 `LogAspect`,用于在方法执行前后打印日志: ```java @Aspect @Component public class LogAspect { @Before("execution(* com.example.UserService.*(..))") public void beforeMethod(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("调用方法:" + methodName + ",参数:" + Arrays.toString(args)); } @AfterReturning("execution(* com.example.UserService.*(..))") public void afterMethod(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); System.out.println("方法调用结束:" + methodName); } } ``` 最后,在Spring配置文件中配置相关的bean和切面: ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="userService" class="com.example.UserServiceImpl"/> <bean id="logAspect" class="com.example.LogAspect"/> <aop:aspectj-autoproxy/> </beans> ``` 以上代码示例中,切面类 `LogAspect` 使用了 `@Aspect` 注解标识为一个切面,并通过 `@Before` 和 `@AfterReturning` 注解定义了前置通知和后置通知的逻辑。在Spring配置文件中,使用 `<aop:aspectj-autoproxy/>` 开启了自动代理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值