Skip to content

Instantly share code, notes, and snippets.

@Haoxiqiang
Created August 16, 2021 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Haoxiqiang/451986420d135ef613145a57779a52e2 to your computer and use it in GitHub Desktop.
Save Haoxiqiang/451986420d135ef613145a57779a52e2 to your computer and use it in GitHub Desktop.
Copy object's all fields by reflect
inline fun <reified T : Any> mergeFields(from: T, to: T, acceptNULL: Boolean = false) {
from::class.java
.declaredFields
.forEach { field ->
val isLocked = field.isAccessible
field.isAccessible = true
val value = field.get(from)
if (acceptNULL || value != null) {
field.set(to, field.get(from))
}
field.isAccessible = isLocked
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment