Reflection 厭倦了嗎?

Andrew Chen
2 min readOct 31, 2019

--

先拿個 Class 然後再拿個 Method ,因為有 overloading ,拿 Method 時,要還帶參數型別帶滿,接著再執行。

例如:

fun getSystemPropertiesInt(key: String, defaultValue: Int = 0): Int? =
try {
val clazz = Class.forName("android.os.SystemProperties")
val getIntMethod = clazz.getMethod("getInt", String::class.java, Int::class.java)
getIntMethod.invoke(clazz, key, defaultValue) as? Int?
} catch (e: Throwable) { null }

fun getSystemProperties(key: String, defaultValue: String? = null): String? =
try {
val clazz = Class.forName("android.os.SystemProperties")
val getMethod = clazz.getMethod("get", String::class.java, String::class.java)
getMethod.invoke(clazz, key, defaultValue) as? String?
} catch (e: Throwable) { null }

讓我們更整潔的包裝一下吧:

除了基本的 function extension 技術,主要還透過原本的參數型別來帶入 getMethod ,所以看起來更簡潔。

年代久遠,忘記有沒有分享過

--

--

No responses yet