我正在學習Kotlin,目前使用Fedora 25 OpenJDK 8和Kotlin 1.1。Kotlin Reflection運算符得到實現
我複製了Kotlin網站的示例:https://kotlinlang.org/docs/reference/delegated-properties.html並更改了get運算符。
class Example {
var p: String by Delegate()
}
class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
// My implementation
return property.getter.call(thisRef) as String
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value has been assigned to '${property.name} in $thisRef.'")
}
}
閱讀反思文檔,吸氣預計的對象實例,並沒有其他的參數,但我只取得了以下錯誤。 (錯誤的縮寫,因爲它太大了,它在遞歸。)
.
.
.
at info.malk.Example.getP(Delegation.kt)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at kotlin.reflect.jvm.internal.FunctionCaller$Method.callMethod(FunctionCaller.kt:98)
at kotlin.reflect.jvm.internal.FunctionCaller$InstanceMethod.call(FunctionCaller.kt:115)
at kotlin.reflect.jvm.internal.KCallableImpl.call(KCallableImpl.kt:107)
at info.malk.Delegate.getValue(Delegation.kt:32)
at info.malk.Example.getP(Delegation.kt)
.
.
.
Caused by: java.lang.reflect.InvocationTargetException
... 1024 more
Caused by: java.lang.StackOverflowError
... 1024 more
Process finished with exit code 1
幫助。
您遞歸調用了'p'吸氣。你想達到什麼目標? – nhaarman
我懷疑是這種情況,我想通過反射/委派來實現getter的幫助。 – Malkaviano