diff --git a/docs/api/public/ReflectionFactory.md b/docs/api/public/ReflectionFactory.md index 48820e2b..bdf04d50 100644 --- a/docs/api/public/ReflectionFactory.md +++ b/docs/api/public/ReflectionFactory.md @@ -389,10 +389,18 @@ inline fun Class<*>.constructor(initiate: ConstructorFinder.() -> Unit): Constru inline fun T.current(initiate: CurrentClass.() -> Unit): T ``` +```kotlin +inline fun T.current(): CurrentClass +``` + **变更记录** `v1.0.70` `新增` +`v1.0.93` `新增` + +新增不使用 `current { ... }` 调用域直接使用 `current()` 得到实例的类操作对象 + **功能描述** > 获得当前实例的类操作对象。 diff --git a/docs/guide/special-feature.md b/docs/guide/special-feature.md index 5d767014..abfd6a17 100644 --- a/docs/guide/special-feature.md +++ b/docs/guide/special-feature.md @@ -563,6 +563,53 @@ instance.current { } ``` +如果你不喜欢使用一个大括号的调用域来创建当前实例的命名空间,你可以直接使用 `current()` 方法。 + +> 示例如下 + +```kotlin +// 假设这就是这个 Class 的实例,这个 Class 是不能被直接得到的 +val instance = Test() +// 执行 doTask 方法 +instance + .current() + .method { + name = "doTask" + param(StringType) + }.call("task_name") +// 执行 stop 方法 +instance + .current() + .method { + name = "stop" + emptyParam() + }.call() +// 得到 name +val name = instance.current().method { name = "getName" }.string() +``` + +同样地,它们之间可以连续调用,但**不允许内联调用**。 + +> 示例如下 + +```kotlin +// 假设这就是这个 Class 的实例 +val instance = Test() +// 假设这个 Class 是不能被直接得到的 +instance.current { + method { + name = "doTask" + param(StringType) + }.call("task_name") +}.current() + .method { + name = "stop" + emptyParam() + }.call() +// ❗注意,因为 current() 返回的是 CurrentClass 自身对象,所以不能像下面这样调用 +instance.current().current() +``` + 问题又来了,我想使用反射的方式创建如下的实例并调用其中的方法,该怎么做呢? > 示例如下 diff --git a/yukihookapi/src/api/kotlin/com/highcapable/yukihookapi/hook/factory/ReflectionFactory.kt b/yukihookapi/src/api/kotlin/com/highcapable/yukihookapi/hook/factory/ReflectionFactory.kt index ba0b2cba..0e9c242b 100644 --- a/yukihookapi/src/api/kotlin/com/highcapable/yukihookapi/hook/factory/ReflectionFactory.kt +++ b/yukihookapi/src/api/kotlin/com/highcapable/yukihookapi/hook/factory/ReflectionFactory.kt @@ -147,10 +147,20 @@ inline fun Class<*>.constructor(initiate: ConstructorFinder.() -> Unit = { empty * @return [T] */ inline fun T.current(initiate: CurrentClass.() -> Unit): T { + if (javaClass.name == CurrentClass::class.java.name) error("Cannot create itself within CurrentClass itself") CurrentClass(javaClass, self = this).apply(initiate) return this } +/** + * 获得当前实例的类操作对象 + * @return [CurrentClass] + */ +inline fun T.current(): CurrentClass { + if (javaClass.name == CurrentClass::class.java.name) error("Cannot create itself within CurrentClass itself") + return CurrentClass(javaClass, self = this) +} + /** * 通过构造方法创建新实例 - 任意类型 [Any] * @param param 方法参数