You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fun <T> pass() =MethodHook<T>(null).apply { pass =true }
100
+
fun <T> intercept(ret:T? = null) =MethodHook(ret)
101
+
}
102
+
}
103
+
```
104
+
- generic T is the return type of the target method, if the target method has no return type, then T is Unit
105
+
-`MethodHook.pass()` means continue to execute the target method
106
+
-`MethodHook.intercept()` means intercept the target method, if the target method has a return value, you can specify the return value through `MethodHook.intercept(ret)`
107
+
108
+
after the above code is compiled, the implementation of Logger#log method will become like this:
109
+
```kotlin
110
+
packagecom.example
111
+
112
+
classLogger {
113
+
val tag ="Logger"
114
+
funlog(msg:String) {
115
+
val methodHook =LoggerEntryHook.hookLogEntry(this, msg)
116
+
if (methodHook.pass) {
117
+
println(msg)
118
+
}
119
+
}
120
+
}
121
+
```
122
+
123
+
### 2. Replace target method completely
124
+
125
+
```kotlin
126
+
@Target(AnnotationTarget.FUNCTION)
127
+
@Retention(AnnotationRetention.SOURCE)
128
+
annotationclassReplace(
129
+
valclassName:String, // 目标方法所在类的全限定名
130
+
valmethodName:String, // 目标方法名
131
+
valparamsTypes:String, // 目标方法参数类型列表,以逗号分隔
132
+
valignoreSuper:Boolean = false// 是否忽略调用 super
133
+
)
134
+
```
135
+
136
+
for example, we think that an exception may occur in the log method, and we want to replace the log method to print the exception information when an exception occurs. We can write like this:
137
+
```kotlin
138
+
object LoggerHook {
139
+
@Replace(
140
+
className ="com.example.Logger",
141
+
methodName ="log",
142
+
paramsTypes ="(kotlin.String)"
143
+
)
144
+
funreplaceLog(caller:Logger, msg:String) {
145
+
try {
146
+
println(msg)
147
+
} catch (e:Exception) {
148
+
e.printStackTrace()
149
+
}
150
+
}
151
+
}
152
+
```
153
+
Be careful, @Replace does not need to be used with MethodHook. The plugin will completely replace the implementation of the target method with the implementation of the annotation method.
0 commit comments