11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://bintray.com/wusealking/maven/wu.seal.android.kotlinreflecttools#)
2 | [](https://github.com/wuseal/Kotlin-Reflect-Tools-For-Android/stargazers)
3 | [](https://github.com/wuseal/Kotlin-Reflect-Tools-For-Android/blob/master/LICENSE)
4 | # Kotlin-Reflect-Tools-For-Android
5 | Kotlin reflect tools for Android
6 |
7 | Related Project: [Kotlin-Reflect-Tools-For-JVM](https://github.com/wuseal/Kotlin-Reflect-Tools-For-JVM)
8 |
9 | ## OverView
10 | This is a tool library for Kotlin to use java reflect APIs in Kotlin simply method on android platform. It can modify or read the top level private visible property value in Kotlin way.
11 |
12 | ## Usage
13 | * Add jcenter repository in your moduel build gradle:
14 | ```groovy
15 | repositories {
16 | jcenter()
17 | }
18 | ```
19 |
20 | * Apply library in dependency config:
21 |
22 | ```groovy
23 | compile 'wu.seal:kotlin-reflect-tools-for-android:1.1.2'
24 | ```
25 |
26 | ## APIs
27 |
28 | |Method | Describe |
29 | |:------------- |:-------------|
30 | |Any.getPropertyValue(propertyName: String): Any?|get object property value by name|
31 | |Any.changePropertyValue(propertyName: String, newValue: Any?) |change object property value by name|
32 | |Any.changePropertyValueByPropertyReference(kProperty: KProperty, newValue: Any?)|change object property value by property reference|
33 | |Any.invokeMethod(methodName: String, vararg args: Any?): Any?|invoke a method through object by method name|
34 | | KProperty.changeValue(thisObj: Any, newValue: Any?)|change current this property valuev|
35 | | KProperty.packageLevelGetPropertyValueByName(otherPropertyName: String): Any? |get other package level property value by other package level property name which is in the same kotlin file|
36 | | KFunction.packageLevelGetPropertyValueByName(otherPropertyName: String): Any?|get other package level property value by other package level property name which is in the same kotlin file|
37 | | KProperty.packageLevelChangePropertyValue(newValue: Any?)|change package level property value|
38 | | KProperty.packageLevelChangeOtherPropertyValueByName(otherPropertyName: String, newValue: Any?)|change other package level property value by other package level property name which is in the same kotlin file|
39 | | KFunction.packageLevelChangeOtherPropertyValueByName(otherPropertyName: String, newValue: Any?)|change other package level property value by other package level property name which is in the same kotlin file|
40 | | KProperty.packageLevelInvokeMethodByName(methodName: String, vararg args: Any?): Any? |invoke package level method by name which is in the same kotlin file|
41 | | KFunction.packageLevelInvokeMethodByName(methodName: String, vararg args: Any?): Any?|invoke package level method by name which is in the same kotlin file|
42 |
43 | All method don't care what the property or method visibility it is
44 |
45 | ## Demo
46 | For example a Kotlin file like this:
47 | ```kotlin
48 |
49 | val topName = "topSeal"
50 | val topNameWu = "topSealWu"
51 | private val topAge = 666
52 |
53 | private fun gotIt() = true
54 |
55 | fun funDoubleAge(age: Int): Int {
56 | return age * 2
57 | }
58 |
59 | class TestDemo {
60 | private val name = "seal"
61 | val age = 28
62 |
63 | private fun isMan(): Boolean {
64 | return true
65 | }
66 | }
67 | ```
68 | Then we could do these :
69 | ```kotlin
70 |
71 | @Test
72 | fun getPropertyValue() {
73 | val demo = TestDemo()
74 | val nameValue = demo.getPropertyValue("name")
75 | nameValue.should.be.equal("seal")
76 | }
77 |
78 | @Test
79 | fun changePropertyValue() {
80 | val demo = TestDemo()
81 | val originValue = demo.age
82 | demo.changePropertyValue("age", 100)
83 | val nowValue = demo.age
84 | originValue.should.not.equal(nowValue)
85 | nowValue.should.be.equal(100)
86 | }
87 |
88 | @Test
89 | fun changeValue() {
90 | val demo = TestDemo()
91 | demo::age.changeValue(demo, 100)
92 | demo.age.should.be.equal(100)
93 | }
94 |
95 | @Test
96 | fun packageLevelGetPropertyValueByName() {
97 | val topAge = ::topNameWu.packageLevelGetPropertyValueByName("topAge")
98 | topAge.should.be.equal(666)
99 | }
100 |
101 | @Test
102 | fun packageLevelInvokeMethodByName() {
103 | val methodResult = ::topName.packageLevelInvokeMethodByName("gotIt") as Boolean
104 | methodResult.should.be.`true`
105 | }
106 |
107 | ```
108 |
109 | To see more usage cases ,you can have a look at the AndroidTest case in project.
110 |
111 | ## Others
112 | * Welcome to raise any issue.
113 | * Welcome to push a pull request
114 |
115 |
116 | ## Find me useful ? :heart:
117 | * Support me by clicking the :star: button on the upper right of this page. :v:
118 |
119 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | apply plugin: 'kotlin-android'
4 |
5 | apply plugin: 'kotlin-android-extensions'
6 |
7 | android {
8 | compileSdkVersion 26
9 | defaultConfig {
10 | applicationId "wu.seal.kotlinreflecttoolsforandroid.demo"
11 | minSdkVersion 15
12 | targetSdkVersion 26
13 | versionCode 1
14 | versionName "1.0"
15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | }
24 |
25 | dependencies {
26 | implementation fileTree(include: ['*.jar'], dir: 'libs')
27 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
28 | implementation 'com.android.support:appcompat-v7:26.1.0'
29 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
30 | testImplementation 'junit:junit:4.12'
31 | androidTestImplementation 'com.android.support.test:runner:1.0.1'
32 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
33 | implementation project(':kotlin-reflect-tools-for-android')
34 | }
35 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/wu/seal/kotlinreflecttoolsforandroid/demo/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.kotlinreflecttoolsforandroid.demo
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getTargetContext()
22 | assertEquals("wu.seal.kotlinreflecttoolsforandroid.demo", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/wu/seal/kotlinreflecttoolsforandroid/demo/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.kotlinreflecttoolsforandroid.demo
2 |
3 | import android.os.Bundle
4 | import android.support.v7.app.AppCompatActivity
5 |
6 | class MainActivity : AppCompatActivity() {
7 |
8 | override fun onCreate(savedInstanceState: Bundle?) {
9 | super.onCreate(savedInstanceState)
10 | setContentView(R.layout.activity_main)
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Kotlin-Reflect-Tools-For-Android
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/wu/seal/kotlinreflecttoolsforandroid/demo/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.kotlinreflecttoolsforandroid.demo
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.1.51'
5 | ext.dokka_version = '0.9.15'
6 | repositories {
7 | google()
8 | jcenter()
9 | }
10 | dependencies {
11 | classpath 'com.android.tools.build:gradle:3.0.1'
12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
13 | classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}"
14 |
15 | // NOTE: Do not place your application dependencies here; they belong
16 | // in the individual module build.gradle files
17 | }
18 | }
19 |
20 | allprojects {
21 | repositories {
22 | google()
23 | jcenter()
24 | }
25 | }
26 |
27 | task clean(type: Delete) {
28 | delete rootProject.buildDir
29 | }
30 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wuseal/Kotlin-Reflect-Tools-For-Android/663241e3d91ad0a8b492db97fe0b510adc49ba95/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Nov 15 16:45:50 CST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id "com.github.dcendents.android-maven" version "2.0"
3 | id "com.jfrog.bintray" version "1.7.3"
4 | }
5 |
6 | apply plugin: 'com.android.library'
7 | apply plugin: 'kotlin-android'
8 | apply plugin: 'org.jetbrains.dokka-android'
9 |
10 |
11 | group = 'wu.seal'
12 | version = '1.1.1'
13 | android {
14 | compileSdkVersion 26
15 | defaultConfig {
16 | minSdkVersion 15
17 | targetSdkVersion 26
18 | versionCode 1
19 | versionName "1.0"
20 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
21 | }
22 |
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 | }
30 | task sourcesJar(type: Jar) {
31 | from android.sourceSets.main.java.srcDirs
32 | classifier = 'sources'
33 | }
34 | task dokkaJavadoc(type: org.jetbrains.dokka.gradle.DokkaTask) {
35 | outputFormat = 'javadoc'
36 | outputDirectory = "$buildDir/javadoc"
37 | }
38 |
39 | task javadocJar(type: Jar, dependsOn: dokkaJavadoc) {
40 | classifier = 'javadoc'
41 | from "$buildDir/javadoc"
42 | }
43 |
44 | artifacts {
45 | archives javadocJar
46 | archives sourcesJar
47 | }
48 |
49 | Properties properties = new Properties()
50 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
51 | bintray {
52 | user = properties.getProperty("BINTRAY_USER")
53 | key = properties.getProperty("BINTRAY_KEY")
54 | configurations = ['archives']
55 | dryRun = false //[Default: false] Whether to run this as dry-run, without deploying
56 | publish = true //[Default: false] Whether version should be auto published after an upload
57 | override = true //[Default: false] Whether to override version artifacts already published
58 | pkg {
59 | repo = 'maven'
60 | name = 'wu.seal.android.kotlinreflecttools'
61 | userOrg = 'wusealking'
62 | licenses = ['Apache-2.0']
63 | vcsUrl = 'https://github.com/wuseal/Kotlin-Reflect-Tools-For-Android'
64 | version {
65 | name = '1.1.1'
66 | desc = 'Fix bug about use reflect API when in overload function condidtion'
67 | released = new Date()
68 | vcsTag = '1.1.1'
69 | }
70 | }
71 | }
72 |
73 | dependencies {
74 | implementation fileTree(dir: 'libs', include: ['*.jar'])
75 |
76 | testImplementation 'junit:junit:4.12'
77 | androidTestImplementation 'com.android.support.test:runner:1.0.1'
78 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
79 | compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
80 | compile "org.jetbrains.kotlin:kotlin-reflect:1.1.51"
81 | androidTestImplementation "com.winterbe:expekt:0.5.0"
82 |
83 | }
84 | repositories {
85 | mavenCentral()
86 | }
87 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/wu/seal/android/kotlinreflecttools/APIExtensionKtTest.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.android.kotlinreflecttools
2 |
3 | import android.support.test.runner.AndroidJUnit4
4 | import com.winterbe.expekt.should
5 | import org.junit.Test
6 | import org.junit.runner.RunWith
7 |
8 | /** API Extension API test
9 | * Created by Seal.Wu on 2018/1/10.
10 | */
11 | @RunWith(AndroidJUnit4::class)
12 | class APIExtensionKtTest {
13 |
14 | @Test
15 | fun getPropertyValue() {
16 | val demo = TestDemo()
17 | val nameValue = demo.getPropertyValue("name")
18 | nameValue.should.be.equal("seal")
19 | }
20 |
21 | @Test
22 | fun changePropertyValue() {
23 | val demo = TestDemo()
24 | val originValue = demo.age
25 | demo.changePropertyValue("age", 100)
26 | val nowValue = demo.age
27 | originValue.should.not.equal(nowValue)
28 | nowValue.should.be.equal(100)
29 | }
30 |
31 | @Test
32 | fun changePropertyValueByPropertyReference() {
33 | val demo = TestDemo()
34 | val originValue = demo.age
35 | demo.changePropertyValueByPropertyReference(demo::age, 100)
36 | val nowValue = demo.age
37 | originValue.should.not.equal(nowValue)
38 | nowValue.should.be.equal(100)
39 | }
40 |
41 | @Test
42 | fun invokeMethod() {
43 | val demo = TestDemo()
44 | val methodResult = demo.invokeMethod("isMan") as Boolean
45 | methodResult.should.be.`true`
46 | }
47 |
48 | @Test
49 | fun changeValue() {
50 | val demo = TestDemo()
51 | demo::age.changeValue(demo, 100)
52 | demo.age.should.be.equal(100)
53 | }
54 |
55 | @Test
56 | fun packageLevelGetPropertyValueByName() {
57 | val topAge = ::topNameWu.packageLevelGetPropertyValueByName("topAge")
58 | topAge.should.be.equal(666)
59 | }
60 |
61 |
62 | @Test
63 | fun packageLevelGetPropertyValueByName1() {
64 | val topAge = ::funDoubleAge.packageLevelGetPropertyValueByName("topAge")
65 | topAge.should.be.equal(666)
66 | }
67 |
68 | @Test
69 | fun packageLevelChangePropertyValue() {
70 | ::topName.packageLevelChangePropertyValue("sealwu")
71 | topName.should.be.equal("sealwu")
72 | }
73 |
74 | @Test
75 | fun packageLevelChangeOtherPropertyValueByName() {
76 | ::topName.packageLevelChangeOtherPropertyValueByName("topNameWu", "seal")
77 | ::topNameWu.packageLevelGetPropertyValueByName("topNameWu").should.be.equal("seal")
78 | }
79 |
80 | @Test
81 | fun packageLevelChangeOtherPropertyValueByName1() {
82 | ::funDoubleAge.packageLevelChangeOtherPropertyValueByName("topNameWu", "seal")
83 | ::topNameWu.packageLevelGetPropertyValueByName("topNameWu").should.be.equal("seal")
84 | }
85 |
86 | @Test
87 | fun packageLevelInvokeMethodByName() {
88 | val methodResult = ::topName.packageLevelInvokeMethodByName("gotIt") as Boolean
89 | methodResult.should.be.`true`
90 | }
91 |
92 | @Test
93 | fun packageLevelInvokeMethodByName1() {
94 | val methodResult = ::funDoubleAge.packageLevelInvokeMethodByName("gotIt") as Boolean
95 | methodResult.should.be.`true`
96 | }
97 |
98 | }
--------------------------------------------------------------------------------
/library/src/androidTest/java/wu/seal/android/kotlinreflecttools/ReflectToolTest.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.android.kotlinreflecttools
2 |
3 |
4 | /**
5 | Created By: Seal.Wu
6 | Date: 2017/11/14
7 | Time: 18:31
8 | */
9 | import android.support.test.runner.AndroidJUnit4
10 | import com.winterbe.expekt.should
11 | import org.junit.Assert.assertEquals
12 | import org.junit.Assert.assertNotEquals
13 | import org.junit.Test
14 | import org.junit.runner.RunWith
15 | import kotlin.jvm.internal.CallableReference
16 |
17 | /**
18 | * test case
19 | * Created by Seal.Wu on 2017/10/27.
20 | */
21 | @RunWith(AndroidJUnit4::class)
22 | class ReflectToolsKtTest {
23 | @org.junit.Before
24 | fun setUp() {
25 |
26 | }
27 |
28 | @org.junit.After
29 | fun tearDown() {
30 | /**
31 | * blow recover the original value of the properties
32 | */
33 | changeTopPropertyValue(::topName, "topSeal")
34 | changeTopPropertyValueByName(::topName as CallableReference, "topAgeName", "666")
35 | changeTopPropertyValueByName(::topName as CallableReference, "topAge", 666)
36 |
37 | }
38 |
39 | @org.junit.Test
40 | fun changeTopPropertyValue() {
41 | val targetName = "fashionSeal"
42 | assertNotEquals(targetName, topName)
43 | changeTopPropertyValue(::topName, targetName)
44 | assertEquals(targetName, topName)
45 | }
46 |
47 | @org.junit.Test
48 | fun changeClassPropertyValue() {
49 | val demoObj = TestDemo()
50 | val preAge = demoObj.age
51 | changeClassPropertyValue(demoObj, demoObj::age, preAge + 1)
52 | assertNotEquals(preAge, demoObj.age)
53 | }
54 |
55 | @org.junit.Test
56 | fun changeClassPropertyValueByName() {
57 | val demoObj = TestDemo()
58 | val preAge = demoObj.age
59 | changeClassPropertyValueByName(demoObj, "age", preAge + 1)
60 | assertNotEquals(preAge, demoObj.age)
61 |
62 | val newValue = "newSeal"
63 | changeClassPropertyValueByName(demoObj, "name", newValue)
64 | assertEquals(newValue, getClassPropertyValueByName(demoObj, "name"))
65 | }
66 |
67 | @org.junit.Test
68 | fun changeTopPropertyValueByName() {
69 |
70 | val targetName = "fashionSeal"
71 | assertNotEquals(targetName, topName)
72 | changeTopPropertyValueByName(::topName as CallableReference, "topName", targetName)
73 | assertEquals(targetName, topName)
74 |
75 | val targetAgeName = "newName"
76 | assertNotEquals(targetAgeName, getTopPropertyValueByName(::topName as CallableReference, "topAgeName"))
77 | changeTopPropertyValueByName(::topName as CallableReference, "topAgeName", targetAgeName)
78 | assertEquals(targetAgeName, getTopPropertyValueByName(::topName as CallableReference, "topAgeName"))
79 |
80 | val targetAge = 18
81 | assertNotEquals(targetAge, getTopPropertyValueByName(::topName as CallableReference, "topAge"))
82 | changeTopPropertyValueByName(::topName as CallableReference, "topAge", targetAge)
83 | assertEquals(targetAge, getTopPropertyValueByName(::topName as CallableReference, "topAge"))
84 | }
85 |
86 | @org.junit.Test
87 | fun getClassPropertyValueByName() {
88 | val expectedNamePropertyValue = "seal"
89 | val demoObj = TestDemo()
90 | val getClassPropertyValue = getClassPropertyValueByName(demoObj, "name")
91 | assertEquals(expectedNamePropertyValue, getClassPropertyValue)
92 | }
93 |
94 | @org.junit.Test
95 | fun getTopPropertyValueByName() {
96 | val expectedTopNamePropertyValue = "topSeal"
97 | val getTopPropertyValue = getTopPropertyValueByName(::funDoubleAge as CallableReference, "topName")
98 | assertEquals(expectedTopNamePropertyValue, getTopPropertyValue)
99 |
100 | val expectedTopAgeName = "666"
101 | val getTopAgeNamePropertyValue = getTopPropertyValueByName(::funDoubleAge as CallableReference, "topAgeName")
102 | assertEquals(expectedTopAgeName, getTopAgeNamePropertyValue)
103 |
104 | val expectedTopAge = 666
105 | val getTopAgePropertyValue = getTopPropertyValueByName(::funDoubleAge as CallableReference, "topAge")
106 | assertEquals(expectedTopAge, getTopAgePropertyValue)
107 |
108 | }
109 |
110 | @org.junit.Test
111 | fun invokeMethodByMethodName() {
112 | val demoObj = TestDemo()
113 | val expectedObjMethodValue = true
114 | val getMethodValue = invokeClassMethodByMethodName(demoObj, "isMan")
115 |
116 | assertEquals(expectedObjMethodValue, getMethodValue)
117 |
118 | }
119 |
120 | @org.junit.Test
121 | fun invokeTopMethodByMethodNameTest() {
122 | val expectedPreTopAge = 665
123 | val expectedNextTopAge = 667
124 |
125 | val invokeMethodPreTopAgeValue = invokeTopMethodByMethodName(::topName as CallableReference, "preTopAge")
126 | val invokeMethodNextTopAgeValue = invokeTopMethodByMethodName(::topName as CallableReference, "nextTopAge")
127 |
128 | assertEquals(expectedPreTopAge, invokeMethodPreTopAgeValue)
129 | assertEquals(expectedNextTopAge, invokeMethodNextTopAgeValue)
130 |
131 |
132 | val testAge = 10
133 | val invokeMethodDoubleAge = invokeTopMethodByMethodName(::topName as CallableReference, "doubleAgeAndPrint", *arrayOf(testAge))
134 | assertEquals(testAge * 2, invokeMethodDoubleAge)
135 |
136 | val testAge1 = 10
137 | val testAg2 = 13
138 | val invokeMethodPlusAge = invokeTopMethodByMethodName(::topName as CallableReference, "plusTwoAge", testAge1, testAg2)
139 | assertEquals(testAge1 + testAg2, invokeMethodPlusAge)
140 |
141 |
142 | val testName = "Seal"
143 | val testAg3 = 18
144 | val invokeMethodPlusNameAge = invokeTopMethodByMethodName(::topName as CallableReference, "plusNameAndAge", testName, testAg3)
145 | assertEquals(testName + testAg3, invokeMethodPlusNameAge)
146 | }
147 |
148 | @Test
149 | fun invokeMethodByMethodNameWithDifferentArguments() {
150 | val demoObj = TestDemo()
151 | val expectedObjMethodValue = false
152 | val getMethodValue = invokeClassMethodByMethodName(demoObj, "isMan", expectedObjMethodValue)
153 | getMethodValue.should.be.equal(expectedObjMethodValue)
154 |
155 | val args = 0.1
156 | val getOtherTypeArgMethodValue = invokeClassMethodByMethodName(demoObj, "isMan", args) as Boolean
157 | getOtherTypeArgMethodValue.should.be.`false`
158 |
159 | }
160 |
161 | @Test
162 | fun invokeMethodByMethodNameWithWrongArguments() {
163 | val demoObj = TestDemo()
164 | val expectedObjMethodValue = false
165 |
166 | val returnValue = try {
167 | invokeClassMethodByMethodName(demoObj, "isMan", "") as Boolean?
168 | } catch (e: Exception) {
169 | false
170 | }
171 | expectedObjMethodValue.should.be.equal(returnValue)
172 |
173 | }
174 |
175 | @Test
176 | fun invokeTopMethodByMethodNameWithDifferentArguments() {
177 | var result = invokeTopMethodByMethodName(::topName as CallableReference, "gotIt")
178 | result.should.be.equal(true)
179 |
180 | result = invokeTopMethodByMethodName(::topName as CallableReference, "gotIt", false)
181 | result.should.be.equal(false)
182 |
183 | result= try {
184 | invokeTopMethodByMethodName(::topName as CallableReference, "gotIt", "Wrong")
185 | } catch (e: Exception) {
186 | "Wrong"
187 | }
188 | result.should.be.equal("Wrong")
189 | }
190 | }
--------------------------------------------------------------------------------
/library/src/androidTest/java/wu/seal/android/kotlinreflecttools/SuperAndSubClass.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.android.kotlinreflecttools
2 |
3 |
4 | /**
5 | Created By: Seal.Wu
6 | Date: 2018/3/29
7 | Time: 10:37
8 | */
9 | open class Super {
10 | private val superFieldOne: String = "superFieldOne"
11 | private val superFieldTwo: Int = 2
12 |
13 |
14 | private fun superPrivateFun(returnValue:Boolean):Boolean {
15 | return returnValue
16 | }
17 |
18 | open fun getSignString():String {
19 | return "Super"
20 | }
21 |
22 | }
23 |
24 | class SubClass : Super() {
25 | private val subFieldOne: String = "subFieldOne"
26 | private val subFieldTwo: Int = 20
27 |
28 | private fun subPrivateFun(returnValue:Boolean):Boolean {
29 | return returnValue
30 | }
31 | override fun getSignString():String {
32 | return "Sub"
33 | }
34 | }
--------------------------------------------------------------------------------
/library/src/androidTest/java/wu/seal/android/kotlinreflecttools/SuperAndSubClassTest.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.android.kotlinreflecttools
2 |
3 | import android.support.test.runner.AndroidJUnit4
4 | import com.winterbe.expekt.should
5 | import org.junit.Test
6 | import org.junit.runner.RunWith
7 |
8 |
9 | /**
10 | Created By: Seal.Wu
11 | Date: 2018/3/29
12 | Time: 10:43
13 | */
14 | @RunWith(AndroidJUnit4::class)
15 | class SuperAndSubClassTest {
16 |
17 | @Test
18 | fun getSuperClassFieldValueTest() {
19 | val obj = SubClass()
20 | obj.getPropertyValue("superFieldOne").should.be.equal("superFieldOne")
21 | }
22 |
23 | @Test
24 | fun invokeSuperClassMethodTest() {
25 | val obj = SubClass()
26 | obj.invokeMethod("superPrivateFun" ,true).should.be.equal(true)
27 | }
28 |
29 | @Test
30 | fun invokeCommonNameFunInSubClass() {
31 | val obj = SubClass()
32 | obj.invokeMethod("getSignString").should.be.equal("Sub")
33 | }
34 |
35 | @Test
36 | fun changeSuperClassFieldValue() {
37 | val obj = SubClass()
38 | val newValue = "newValue"
39 | obj.changePropertyValue("superFieldOne",newValue)
40 | obj.getPropertyValue("superFieldOne").should.be.equal(newValue)
41 | }
42 | }
--------------------------------------------------------------------------------
/library/src/androidTest/java/wu/seal/android/kotlinreflecttools/TestThings.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.android.kotlinreflecttools
2 |
3 | /**
4 | * Created by Seal.Wu on 2017/10/27.
5 | */
6 |
7 |
8 | val topName = "topSeal"
9 | val topNameWu = "topSealWu"
10 | private val topAge = 666
11 | private val topAgeName = "666"
12 |
13 | private fun gotIt() = true
14 | private fun gotIt(boolean: Boolean) = boolean
15 | private fun preTopAge(): Int {
16 | return funPropertyReduceAge(topAge)
17 | }
18 |
19 | private fun nextTopAge(): Int {
20 | return funPropertyPlusAge(topAge)
21 | }
22 |
23 |
24 | private fun doubleAgeAndPrint(age: Int): Int {
25 | val doubleAge = age * 2
26 | println("double age = $doubleAge")
27 | return doubleAge
28 | }
29 |
30 | private fun plusTwoAge(age1: Int, age2: Int): Int {
31 | val plusAge = age1 + age2
32 | println("plus age = $plusAge")
33 |
34 | return plusAge
35 | }
36 |
37 |
38 | private fun plusNameAndAge(name: String, age2: Int): String {
39 | val plusNameAndAge = name + age2
40 | println("wu.seal.jvm.kotlinreflecttools.plusNameAndAge = $plusNameAndAge")
41 |
42 | return plusNameAndAge
43 | }
44 |
45 | val funPropertyPlusAge: (Int) -> Int = { age -> age + 1 }
46 |
47 | val funPropertyReduceAge: (Int) -> Int = { age -> age - 1 }
48 |
49 | fun funDoubleAge(age: Int): Int {
50 | return age * 2
51 | }
52 |
53 | class TestDemo {
54 | private val name = "seal"
55 | val age = 28
56 |
57 | private fun isMan(): Boolean {
58 | return true
59 | }
60 |
61 | private fun isMan(boolean: Boolean) :Boolean{
62 | return boolean
63 | }
64 | private fun isMan(double: Double) :Boolean{
65 | return double==0.0
66 | }
67 |
68 | fun nextAge(): Int {
69 | return age + 1
70 | }
71 | }
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/library/src/main/java/wu/seal/android/kotlinreflecttools/APIExtension.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.android.kotlinreflecttools
2 |
3 | import kotlin.jvm.internal.CallableReference
4 | import kotlin.reflect.KFunction
5 | import kotlin.reflect.KProperty
6 |
7 | /**
8 | * API extension model for easy use
9 | * Created by Seal.Wu on 2018/1/9.
10 | */
11 |
12 | /**
13 | * get object property value by name
14 | */
15 | fun Any.getPropertyValue(propertyName: String): Any? {
16 | return getClassPropertyValueByName(this, propertyName)
17 | }
18 |
19 | /**
20 | * change object property value by name
21 | */
22 | fun Any.changePropertyValue(propertyName: String, newValue: Any?) {
23 | changeClassPropertyValueByName(this, propertyName, newValue)
24 | }
25 |
26 | /**
27 | * change object property value by name
28 | */
29 | fun Any.changePropertyValueByPropertyReference(kProperty: KProperty, newValue: Any?) {
30 | changeClassPropertyValue(this, kProperty, newValue)
31 | }
32 |
33 | /**
34 | * invoke a method through object by method name
35 | *
36 | */
37 | fun Any.invokeMethod(methodName: String, vararg args: Any?): Any? {
38 | return invokeClassMethodByMethodName(this, methodName, *args)
39 | }
40 |
41 | /**
42 | * change current this property value
43 | */
44 | fun KProperty.changeValue(thisObj: Any, newValue: Any?) {
45 | changeClassPropertyValue(thisObj, this, newValue)
46 | }
47 |
48 | /**
49 | * get other package level property value by other package level property name which is in the same kotlin file
50 | */
51 | fun KProperty.packageLevelGetPropertyValueByName(otherPropertyName: String): Any? {
52 | return getTopPropertyValueByName(this as CallableReference, otherPropertyName)
53 | }
54 |
55 | /**
56 | * get other package level property value by other package level property name which is in the same kotlin file
57 | */
58 | fun KFunction.packageLevelGetPropertyValueByName(otherPropertyName: String): Any? {
59 | return getTopPropertyValueByName(this as CallableReference, otherPropertyName)
60 | }
61 |
62 | /**
63 | * change package level property value
64 | */
65 | fun KProperty.packageLevelChangePropertyValue(newValue: Any?) {
66 | changeTopPropertyValue(this, newValue)
67 | }
68 |
69 | /**
70 | * change other package level property value by other package level property name which is in the same kotlin file
71 | */
72 | fun KProperty.packageLevelChangeOtherPropertyValueByName(otherPropertyName: String, newValue: Any?) {
73 | changeTopPropertyValueByName(this as CallableReference, otherPropertyName, newValue)
74 | }
75 |
76 | /**
77 | * change other package level property value by other package level property name which is in the same kotlin file
78 | */
79 | fun KFunction.packageLevelChangeOtherPropertyValueByName(otherPropertyName: String, newValue: Any?) {
80 | changeTopPropertyValueByName(this as CallableReference, otherPropertyName, newValue)
81 | }
82 |
83 |
84 | /**
85 | * invoke package level method by name which is in the same kotlin file
86 | */
87 | fun KProperty.packageLevelInvokeMethodByName(methodName: String, vararg args: Any?): Any? {
88 | return invokeTopMethodByMethodName(this as CallableReference, methodName, *args)
89 | }
90 |
91 | /**
92 | * invoke package level method by name which is in the same kotlin file
93 | */
94 | fun KFunction.packageLevelInvokeMethodByName(methodName: String, vararg args: Any?): Any? {
95 | return invokeTopMethodByMethodName(this as CallableReference, methodName, *args)
96 | }
97 |
98 |
99 |
--------------------------------------------------------------------------------
/library/src/main/java/wu/seal/android/kotlinreflecttools/KotlinRefelectForAndroid.kt:
--------------------------------------------------------------------------------
1 | package wu.seal.android.kotlinreflecttools
2 |
3 | import java.lang.Exception
4 | import java.lang.IllegalArgumentException
5 | import java.lang.IllegalStateException
6 | import java.lang.reflect.Modifier
7 | import java.util.*
8 | import kotlin.jvm.internal.CallableReference
9 | import kotlin.jvm.internal.PropertyReference
10 | import kotlin.reflect.KProperty
11 |
12 | /**
13 | Created By: Seal.Wu
14 | Date: 2017/11/8
15 | Time: 14:24
16 | */
17 |
18 | /**
19 | * change the property value with new value int the special KProperty in package level property ,not the property in class
20 | *
21 | */
22 | fun changeTopPropertyValue(property: KProperty, newValue: R): Boolean =
23 | changePropertyValue(null, property, newValue)
24 |
25 | /**
26 | * change the property value with new value int the special KProperty inside a class level ,not the property not in any class
27 | */
28 | fun changeClassPropertyValue(classObj: Any, property: KProperty, newValue: R): Boolean =
29 | changePropertyValue(classObj, property, newValue)
30 |
31 | private fun changePropertyValue(classObj: Any?, property: KProperty, newValue: R): Boolean {
32 | val owner = (property as PropertyReference).owner
33 | val propertyName = property.name
34 | val containerClass: Class<*>
35 | try {
36 | containerClass = (owner!!::class.members as ArrayList).firstOrNull { it.name == "jClass" }?.call(owner) as Class<*>
37 | } catch (e: Exception) {
38 | throw IllegalArgumentException("No such property 'jClass'")
39 | }
40 |
41 | var tobeSearchFieldClass: Class<*>? = containerClass
42 | while (tobeSearchFieldClass != null) {
43 |
44 | tobeSearchFieldClass.declaredFields.forEach { field ->
45 | if (field.name == propertyName) {
46 | field.isAccessible = true
47 | field.set(classObj, newValue)
48 | return true
49 | }
50 | }
51 |
52 | tobeSearchFieldClass = tobeSearchFieldClass.superclass
53 | }
54 | return false
55 | }
56 |
57 | /**
58 | * change the property value with new value int the special property name inside a class level ,not the property not in any class
59 | */
60 | fun changeClassPropertyValueByName(classObj: Any, propertyName: String, newValue: R): Boolean {
61 | val containerClass: Class<*> = classObj::class.java
62 |
63 | var tobeSearchFieldClass: Class<*>? = containerClass
64 | while (tobeSearchFieldClass != null) {
65 |
66 | tobeSearchFieldClass.declaredFields.forEach { field ->
67 | if (field.name == propertyName) {
68 | field.isAccessible = true
69 | field.set(classObj, newValue)
70 | return true
71 | }
72 | }
73 |
74 | tobeSearchFieldClass = tobeSearchFieldClass.superclass
75 | }
76 | return false
77 | }
78 |
79 | /**
80 | * change the property value with new value int the special Property name in package level property ,not the property in class
81 | */
82 | fun changeTopPropertyValueByName(otherCallableReference: CallableReference, propertyName: String, newValue: Any?) {
83 |
84 | val owner = otherCallableReference.owner
85 | val containerClass: Class<*>
86 | try {
87 | containerClass = (owner!!::class.members as ArrayList).firstOrNull { it.name == "jClass" }?.call(owner) as Class<*>
88 | } catch (e: Exception) {
89 | throw IllegalArgumentException("No such property 'jClass'")
90 | }
91 | var tobeSearchFieldClass: Class<*>? = containerClass
92 |
93 | while (tobeSearchFieldClass != null) {
94 |
95 | tobeSearchFieldClass.declaredFields.forEach { field ->
96 | if (field.name == propertyName) {
97 | field.isAccessible = true
98 | if (Modifier.isStatic(field.modifiers)) {
99 | field.set(null, newValue)
100 | } else {
101 | throw IllegalStateException("It is not a top property : $propertyName")
102 | }
103 | return
104 | }
105 | }
106 | tobeSearchFieldClass = tobeSearchFieldClass.superclass
107 | }
108 | throw IllegalArgumentException("Can't find the property named :$propertyName in the same file with ${otherCallableReference.name}")
109 | }
110 |
111 | /**
112 | * get the property value from a class object ,no matter whether the property is public ,private or intenel
113 | */
114 | fun getClassPropertyValueByName(classObj: Any, propertyName: String): Any? {
115 | val containerClass: Class<*> = classObj::class.java
116 |
117 | var tobeSearchFieldClass: Class<*>? = containerClass
118 |
119 | while (tobeSearchFieldClass != null) {
120 |
121 | tobeSearchFieldClass.declaredFields.forEach { field ->
122 | if (field.name == propertyName) {
123 | field.isAccessible = true
124 |
125 | return field.get(classObj)
126 | }
127 | }
128 | tobeSearchFieldClass = tobeSearchFieldClass.superclass
129 | }
130 |
131 | return null
132 | }
133 |
134 | /**
135 | * get the property value in the top of a kotlin file(not in any kotlin class) ,no matter whether the property is public ,private or internal
136 | */
137 | fun getTopPropertyValueByName(otherCallableReference: CallableReference, propertyName: String): Any? {
138 |
139 | val owner = otherCallableReference.owner
140 | val containerClass: Class<*>
141 | try {
142 | containerClass = (owner!!::class.members as ArrayList).firstOrNull { it.name == "jClass" }?.call(owner) as Class<*>
143 | } catch (e: Exception) {
144 | throw IllegalArgumentException("No such property 'jClass'")
145 | }
146 |
147 | var tobeSearchFieldClass: Class<*>? = containerClass
148 |
149 | while (tobeSearchFieldClass != null) {
150 |
151 | tobeSearchFieldClass.declaredFields.forEach { field ->
152 | if (field.name == propertyName) {
153 | field.isAccessible = true
154 |
155 | /**
156 | * top property(package property) should be static in java level
157 | * or throw an exception
158 | * */
159 | if (Modifier.isStatic(field.modifiers)) {
160 | return field.get(null)
161 | } else {
162 | throw IllegalStateException("It is not a top property : $propertyName")
163 | }
164 | }
165 | }
166 | tobeSearchFieldClass = tobeSearchFieldClass.superclass
167 | }
168 |
169 | throw IllegalArgumentException("Can't find the property named :$propertyName in the same file with ${otherCallableReference.name}")
170 | }
171 |
172 | /**
173 | * invoke a method by name from a classObj,no matter whether the property is public ,private or internal
174 | */
175 | fun invokeClassMethodByMethodName(classObj: Any, methodName: String, vararg methodArgs: Any?): Any? {
176 | val containerClass: Class<*> = classObj::class.java
177 |
178 | var tobeSearchMethodClass: Class<*>? = containerClass
179 |
180 | while (tobeSearchMethodClass != null) {
181 |
182 | tobeSearchMethodClass.declaredMethods.forEach { method ->
183 | if (method.name == methodName && method.parameterTypes.size == methodArgs.size) {
184 | method.isAccessible = true
185 | try {
186 | if (methodArgs.isNotEmpty()) {
187 |
188 | return method.invoke(classObj, *methodArgs)
189 | } else {
190 | return method.invoke(classObj)
191 | }
192 | } catch (e: IllegalArgumentException) {
193 | return@forEach
194 | }
195 | }
196 | }
197 | tobeSearchMethodClass = tobeSearchMethodClass.superclass
198 | }
199 |
200 | throw IllegalArgumentException("Can't find the method named :$methodName with args ${methodArgs.toList().toString()} in the classObj : $classObj")
201 | }
202 |
203 | /**
204 | * invoke a method by name from a kotlin file(not in any kotlin class),no matter whether the property is public ,private or internal
205 | */
206 | fun invokeTopMethodByMethodName(otherCallableReference: CallableReference, methodName: String, vararg methodArgs: Any?): Any? {
207 | val owner = otherCallableReference.owner
208 | val containerClass: Class<*>
209 | try {
210 | containerClass = (owner!!::class.members as ArrayList).firstOrNull { it.name == "jClass" }?.call(owner) as Class<*>
211 | } catch (e: Exception) {
212 | throw IllegalArgumentException("No such property 'jClass'")
213 | }
214 |
215 | var tobeSearchMethodClass: Class<*>? = containerClass
216 |
217 | while (tobeSearchMethodClass != null) {
218 |
219 | tobeSearchMethodClass.declaredMethods.forEach { method ->
220 | if (method.name == methodName && method.parameterTypes.size == methodArgs.size) {
221 | method.isAccessible = true
222 |
223 | try {
224 | if (methodArgs.isNotEmpty()) {
225 | return method.invoke(null, *methodArgs)
226 | } else {
227 | return method.invoke(null)
228 | }
229 | } catch (e: IllegalArgumentException) {
230 | return@forEach
231 | }
232 | }
233 | }
234 | tobeSearchMethodClass = tobeSearchMethodClass.superclass
235 | }
236 | throw IllegalArgumentException("Can't find the method named :$methodName with args ${methodArgs.toList().toString()} in the same file with ${otherCallableReference.name}")
237 |
238 | }
239 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Library
3 |
4 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 | project(':library').name='kotlin-reflect-tools-for-android'
3 |
--------------------------------------------------------------------------------