# What about to call reflect in kotlin like this?

**URL:** <https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835>\
**Category:** Language Design\
**Created:** [January 12, 2020, 4:00am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835 "2020-01-12T04:00:26Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![lorss](https://avatars.discourse-cdn.com/v4/letter/l/3ec8ea/32.png) [@lorss](https://discuss.kotlinlang.org/u/lorss)\
**Post date:** [January 12, 2020, 4:00am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835/1 "2020-01-12T04:00:27Z")

</div>

Click[\>\>\> Click to see source code](https://github.com/runningmessage/kotlinx-android/blob/master/app/src/main/java/com/runningmessage/kotlinx/demo/reflect/ReflectDemo.kt)

# ========================== Call method by reflect

```java

        private lateinit var activity: Any

        activity.runInActivity()

        private fun Any.runInActivity() {// In the code below , [this] is Activity Object

            /***
             * setContentView(R.layout.activity_main)
             * ***/
            calls("setContentView")(R.layout.activity_main)

            /***
             * val npRecyclerView = findViewById<ViewGroup>(R.id.npRecyclerView)
             * ***/
            val npRecyclerView = call<ViewGroup>("findViewById")(R.id.npRecyclerView)

            /***
             * val npRefreshLayout = findViewById<ViewGroup>(R.id.npRefreshLayout)
             * ***/
            val npRefreshLayout = call<ViewGroup>("findViewById")(R.id.npRefreshLayout)

            ... ...

         }

```

# ========================== Create Instance by reflect

```java

        / *****************************Import to reflect***************************** /
        / **The string below can be used just same as declared class in the code** /

        private const val MyLoadMoreRecyclerAdapter = "com.runningmessage.kotlinx.demo.MyLoadMoreRecyclerAdapter"
        private const val StaggeredGridLayoutManager = "android.support.v7.widget.StaggeredGridLayoutManager"

        private fun Any.runInActivity() {// In the code below , [this] is Activity Object

            ... ..

            // set the load more recycler adapter
            val applicationContext = call<Context>("getApplicationContext")()

            /***
             * the declared string [MyLoadMoreRecyclerAdapter] can be used same as class which is imported
             *
             * val adapter = com.runningmessage.kotlinx.demo.MyLoadMoreRecyclerAdapter(applicationContext)
             * ***/
            val adapter: Any? = MyLoadMoreRecyclerAdapter(applicationContext)

            /***
             * the declared string [StaggeredGridLayoutManager] can be used same as class which is imported
             *
             * npRecyclerView.setLayoutManager(StaggeredGridLayoutManager(2, 1))
             * ***/
            npRecyclerView.calls("setLayoutManager")(StaggeredGridLayoutManager(2, 1))

            ... ...
        }

```

# ========================== Call property by reflect

```java

        private fun Any.runInActivity() {// In the code below , [this] is Activity Object

            ... ..

            /***
             * adapter.isAutoLoadMore = false
             ***/
            adapter.propertys("isAutoLoadMore").value = false

            /***
             * val count = adapter.dataCount
             ***/
            val count = adapter.property<Int>("dataCount").value ?: 0

            ... ...
        }

```

# ========================== Create Anonymous inner class instance

```java

        / *****************************Import to reflect***************************** /
        / **The string below can be used just same as declared class in the code** /

        private const val OnLoadMoreListener = "com.runningmessage.kotlinx.widget.LoadMoreRecyclerAdapter${'$'}OnLoadMoreListener"
        private const val OnRefreshListener = "com.runningmessage.kotlinx.widget.AbsSwipeRefreshLayout${'$'}OnRefreshListener"

        private fun Any.runInActivity() {// In the code below , [this] is Activity Object

            ... ..

            /***
             * adapter.onLoadMoreListener = object: OnLoadMoreListener{
             *
             * override fun onLoadMore(){
             * // do something
             * }
             *
             * }
             * ***/
            adapter.propertys("onLoadMoreListener").value = OnLoadMoreListener.createInners {

                override("onLoadMore") {

                    // do something
                }
            }

            /***
             * npRefreshLayout.setOnRefreshListener = object: OnRefreshListener{
             *
             * override fun onRefresh(autoNotify: Boolean){
             * // do something
             * }
             *
             * }
             * ***/
            npRefreshLayout.calls("setOnRefreshListener")(OnRefreshListener.createInners {

                override("onRefresh") {
                    val autoNotify: Boolean = it?.get(0) as? Boolean ?: false

                    // do something
                }
            })

        }

```

---

<div class="post-metadata">

**Author:** ![lorss](https://avatars.discourse-cdn.com/v4/letter/l/3ec8ea/32.png) [@lorss](https://discuss.kotlinlang.org/u/lorss)\
**Post date:** [January 13, 2020, 4:43am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835/2 "2020-01-13T04:43:36Z")

</div>

[\>\> \>\> Click to see source code](https://github.com/runningmessage/kotlinx-android/blob/master/app/src/main/java/com/runningmessage/kotlinx/demo/reflect/ReflectDemo.kt)

# ========================== Opt the method [createInner] to Create Anonymous inner class instance

```java

        / *****************************Import to reflect***************************** /
        / **The string below can be used just same as declared class in the code** /
        private const val OnRefreshListener = "com.runningmessage.kotlinx.widget.AbsSwipeRefreshLayout${'$'}OnRefreshListener"

        private fun Any.runInActivity() {// In the code below , [this] is Activity Object

            ... ..

            /***
             * npRefreshLayout.setOnRefreshListener = object: OnRefreshListener{
             *
             * override fun onRefresh(autoNotify: Boolean){
             * // do something
             * }
             *
             * }
             * ***/
            npRefreshLayout.calls("setOnRefreshListener")(OnRefreshListener.createInners {

                override<Boolean>("onRefresh") { autoNotify ->
                    val autoNotifyNo = autoNotify ?: false

                    // do something
                }
            })

        }

```

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [January 13, 2020, 5:17am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835/3 "2020-01-13T05:17:23Z")

</div>

I don’t really understand what the problem is that you try to solve. In what way is this version supperior to the current reflect api or is there anything that you want to do that you can’t with the current api, but yours allows for.  
Right now you just have some example usage code, which to be honest I don’t fully understand.

---

<div class="post-metadata">

**Author:** ![lorss](https://avatars.discourse-cdn.com/v4/letter/l/3ec8ea/32.png) [@lorss](https://discuss.kotlinlang.org/u/lorss)\
**Post date:** [January 13, 2020, 5:44am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835/4 "2020-01-13T05:44:21Z")

</div>

I just want to supply some utility code which makes calling reflect simply, rather than changing the kotlin api.

You can click the link above to see implement source code, Which api called in the demo and is just functions wrap the kotlin reflect apis.

---

<div class="post-metadata">

**Author:** ![lorss](https://avatars.discourse-cdn.com/v4/letter/l/3ec8ea/32.png) [@lorss](https://discuss.kotlinlang.org/u/lorss)\
**Post date:** [January 14, 2020, 8:55am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835/5 "2020-01-14T08:55:42Z")

</div>

[\>\>\> Click to see main class ReflectExt.kt](https://github.com/runningmessage/kotlinx-android/blob/master/kotlinx-reflect/src/main/java/com/runningmessage/kotlinx/reflect/ReflectExt.kt)

The source code has uploaded to [bintray jcenter](https://bintray.com/beta/#/runningmessage/maven/kotlinx-reflect?tab=readme), now you can import the code in gradle like this:

```nohighlight

    //project build.gradle
    buildscript {
        repositories {
            ...

            //add the maven url
            maven { url "https://dl.bintray.com/runningmessage/maven" }
        }
    }

    //app build.gradle
    compile 'com.runningmessage.kotlinx-android:kotlinx-reflect:0.0.7'

```

---

<div class="post-metadata">

**Author:** ![lorss](https://avatars.discourse-cdn.com/v4/letter/l/3ec8ea/32.png) [@lorss](https://discuss.kotlinlang.org/u/lorss)\
**Post date:** [January 15, 2020, 4:23am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835/6 "2020-01-15T04:23:30Z")

</div>

[\>\>\> Click to see main class ReflectExt.kt](https://github.com/runningmessage/kotlinx-android/blob/master/kotlinx-reflect/src/main/java/com/runningmessage/kotlinx/reflect/ReflectExt.kt)

the document for almost all function has update in ReflectExt.kt, if you are interested , you can click the above link to see .

---

<div class="post-metadata">

**Author:** ![lorss](https://avatars.discourse-cdn.com/v4/letter/l/3ec8ea/32.png) [@lorss](https://discuss.kotlinlang.org/u/lorss)\
**Post date:** [January 16, 2020, 4:30am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835/7 "2020-01-16T04:30:16Z")

</div>

[\>\>\> Click to see main class ReflectExt.kt](https://github.com/runningmessage/kotlinx-android/blob/master/kotlinx-reflect/src/main/java/com/runningmessage/kotlinx/reflect/ReflectExt.kt)

# ======== add api [Any?.ifIs] to make reflective call like " if (a is String){}"

````java
/**
 * Do something in [block] if the type of receiver [this][Any] is subclass of [KClass] which class name is [className],
 *
 * then try to return the value which type is [R]?
 *
 * [Demo].[Code].
 *
 * ```java
 *
 * val AppCompatActivity = "android.support.v7.app.AppCompatActivity"
 *
 * lateinit var activity: Any
 *
 * activity.ifIs(AppCompatActivity) { appCompatActivity: Any ->
 * appCompatActivity.runInActivity()
 * }
 *
 * // another sample
 * val context: Context? = activity.ifIs(AppCompatActivity) { appCompatActivity: Any ->
 * return@ifIs appCompatActivity.call<Context>("getApplicationContext")()
 * }
 *
 * ```
 */
fun <T : Any, R> Any?.ifIs(className: String, block: (T) -> R): R?

````

---

<div class="post-metadata">

**Author:** ![lorss](https://avatars.discourse-cdn.com/v4/letter/l/3ec8ea/32.png) [@lorss](https://discuss.kotlinlang.org/u/lorss)\
**Post date:** [January 16, 2020, 8:44am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835/8 "2020-01-16T08:44:30Z")

</div>

[\>\>\> Click to see main class ReflectExt.kt](https://github.com/runningmessage/kotlinx-android/blob/master/kotlinx-reflect/src/main/java/com/runningmessage/kotlinx/reflect/ReflectExt.kt)

# ======== Create anonymous inner class instance

By Reflective calling , to override the abstract method in an interface when implement it, you have **the below three ways**.

```java
        val TextWatcher = "android.text.TextWatcher"

        val watcher = TextWatcher.createInners{
        
        
            override<CharSequence, Int, Int, Int>("beforeTextChanged"){
                s, start, before, count ->
            
            }
            
            override("onTextChanged"){
                s: CharSequence?, start: Int?, before: Int?, count: Int? ->
            
            }
            
            override("afterTextChanged", CallHandlerFunction { args: Array<out Any?>? ->
                val s = args?.get(0) as? Editable
            })
        }

```

---

<div class="post-metadata">

**Author:** ![lorss](https://avatars.discourse-cdn.com/v4/letter/l/3ec8ea/32.png) [@lorss](https://discuss.kotlinlang.org/u/lorss)\
**Post date:** [January 16, 2020, 11:00am UTC](https://discuss.kotlinlang.org/t/what-about-to-call-reflect-in-kotlin-like-this/15835/9 "2020-01-16T11:00:30Z")

</div>

[\>\>\> click to see README](https://github.com/runningmessage/kotlinx-android) and scroll to title **kotlinx-reflect** see more **demo code**.
