Created
November 5, 2019 14:46
-
-
Save Schwusch/ee8c7430b4da57f73dcc0d053fcea5cd to your computer and use it in GitHub Desktop.
A hacky way of updating an object with another objects data. This is a really bad pattern kids
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Loops through all fields in the receiving object and looks for fields | |
* with the same name in the sending object. Then it tries to copy non-null | |
* values to the receiving object, and silently fails when something goes wrong | |
* | |
* Don't use this | |
*/ | |
fun Any.update(new: Any) = javaClass.declaredFields.forEach { field -> | |
try { | |
field.isAccessible = true | |
new.javaClass.getDeclaredField(field.name).also { | |
it.get(new)?.let { value -> | |
field.set(this, value) | |
} | |
} | |
} catch (e: Exception) { | |
println(e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment