I’m experimenting with property delegates + JPA.
I implemented a very simple property delegate:
class MutableNonSynchronizedLazy<T>(private val init: () -> T) : ReadWriteProperty<Any?, T> {
private var value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (value == null) {
value = init()
}
return value!!
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
}
fun <T> mutableNonSynchronizedLazy(init: () -> T) = MutableNonSynchronizedLazy(init)
My problem is that I don’t find a way to add an annotation to a field delegated by MutableNonSynchronizedLazy
:
@Entity
class SomeEntity {
@field:ElementCollection(fetch = FetchType.EAGER)
var map: Map<String, String?> by mutableNonSynchronizedLazy { HashMap<String, String?>() }
}
I get the error:
‘@field:’ annotations could be applied only to properties with backing fields
Maybe is there a way to use the “original” backing field of the property in the delegate’s getValue()
and setValue()
methods?
(I know that it is possible to define JPA annotations on getters instead of fields - but I prefer the latter.)