终于有时间写一篇hook的文章了。
反射和Hook的相同点和不同点是什么?
都是使用字节码,但是反射是利用字节码获取对象,修改对象的属性而Hook是修改字节码的执行逻辑和内容
说起来有点抽象,举个例子:
美国男篮和中国男篮举行篮球赛,每个队伍都有1,2,3,4,5号队员。
中国1号队员又不认识美国1号队员,那么是怎么盯防1号队员的呢?对的,会有一个1号球衣,他只要看球衣就行了,美国人长得都一样不用仔细看脸,美国队员也是这么盯防中国队的
中国队觉得美国队实力很强,比赛之前排兵布阵将12和45队员位置互换,然后组成45312阵容和美国12345阵容竞赛。
美国队和中国队表示两个java文件,12345表示字节码顺序,比赛表示代码执行
反射就是中国队想要盯防美国队(java类调用另一个Java类但是无法引用怎么办?等我们执行的时候就都在一起了,我使用包名.类名找到你,知道你的属性和你的方法,可以完整地控制你的一举一动)
hook修改了原有队员的比赛顺序,修改了字节码的执行逻辑和顺序,可以安插一些钩子函数,嵌入自己的代码。
下面开始Aspectjx的集成使用
我的Android Studio 版本 3.6.2,如果代码不生效很有可能是Android Studio版本和aspectjx版本不兼容的问题
附上demo地址 Aspectjx demo
Root build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.2'
classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.10'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
apply plugin: 'com.android.application'
apply plugin: 'android-aspectjx'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.test"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
aspectjx {
//排除所有package路径中包含`android.support`的class文件及库(jar文件)
exclude 'android.support'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
package com.test;
import android.util.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class AspectjxMine {
@Pointcut("execution(* com.test.MainActivity.clickMe(..))")
public void callMethod() {
}
@Around("callMethod()")//
public void beforeMethodCall(ProceedingJoinPoint joinPoint) {
try {
Log.i("TAG", "callMethod before ");
joinPoint.proceed();
Log.i("TAG", "callMethod after ");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}