Skip to content

Instantly share code, notes, and snippets.

@Schwusch
Created November 5, 2019 14:46
Show Gist options
  • Save Schwusch/ee8c7430b4da57f73dcc0d053fcea5cd to your computer and use it in GitHub Desktop.
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
/**
* 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