Created
December 12, 2023 04:02
-
-
Save sugihaya/d94bc4a8e5fabe68002caec535f91c54 to your computer and use it in GitHub Desktop.
リフレションを使った自作assert
This file contains 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
fun assertAllPropertiesNotNull(obj: Any) { | |
obj::class.memberProperties | |
.forEach { p -> | |
val value = (p as KProperty1<Any?, *>).get(obj) ?: throw AssertionFailedError("${p.name} is null", null, null) | |
assertNotNull(value, "${p.name} is null") | |
if (value.isUncheckType()) { | |
return@forEach // continue | |
} | |
// recursive | |
if (value is Collection<*>) { | |
value.forEach collectionForEach@ { element -> | |
if (element == null) { | |
throw AssertionFailedError("${p.name} contains null") | |
} | |
if (element.isUncheckType()) { | |
return@collectionForEach // continue | |
} | |
assertAllPropertiesNotNull(element, excludePropertyNames) | |
} | |
return@forEach // continue | |
} | |
// recursive | |
assertAllPropertiesNotNull(value, excludePropertyNames) | |
} | |
} | |
// POJO or プリミティブさえ判定できればいいがもっといい方法がないか | |
fun Any.isUncheckType() = when(this) { | |
is String, is Int, is Long, is Double, is Float, is Boolean -> true | |
else -> false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
すべてのプロパティがnull以外の値で初期化されているか?などを検証するために使うことを想定