Last active
April 18, 2021 15:18
-
-
Save Coronel-B/88ac762bee486eb83ded694a055da6d7 to your computer and use it in GitHub Desktop.
Exclude property in toString () method
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
import java.lang.reflect.Field | |
import java.util.* | |
/** | |
* SPDX-License-Identifier: MIT | |
*/ | |
/** | |
* Source: https://kotlinlang.org/docs/tutorials/kotlin-for-py/annotations.html | |
*/ | |
@Target(AnnotationTarget.FIELD) | |
@Retention(AnnotationRetention.RUNTIME) | |
annotation class ExcludeToString | |
data class Test( | |
var a: String = "A", | |
@ExcludeToString var b: String = "B", | |
var c: String = "C", | |
) { | |
// Output: Test=[a=A, c=C] | |
override fun toString(): String { | |
return ExcludeToStringUtils.getToString(this) | |
} | |
} | |
object ExcludeToStringUtils { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
print(Test().toString()) | |
} | |
/** | |
* Formats the object with their respective fields | |
* Source: https://stackoverflow.com/a/44653046/5279996 | |
*/ | |
fun getToString(obj: Any): String { | |
val toString = LinkedList<String>() | |
getFieldsNotExludeToString(obj).forEach { prop -> | |
prop.isAccessible = true | |
toString += "${prop.name}=" + prop.get(obj)?.toString()?.trim() | |
} | |
return "${obj.javaClass.simpleName}=[${toString.joinToString(", ")}]" | |
} | |
/** | |
* Filter the fields that do not have annotation @ExcludeToString | |
*/ | |
private fun getFieldsNotExludeToString(obj: Any): List<Field> { | |
val declaredFields = obj::class.java.declaredFields | |
return declaredFields.filterNot { field -> | |
isFieldWithExludeToString(field) | |
} | |
} | |
/** | |
* Determine if a field has annotation @ExcludeToString | |
*/ | |
private fun isFieldWithExludeToString(field: Field): Boolean { | |
field.annotations.forEach { | |
if (it.annotationClass == ExcludeToString::class) { | |
return true | |
} | |
} | |
return false | |
} | |
} |
I'm glad it worked for you. A short license identifier of MIT were added. Any feedback is welcome. Thanks to you
👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for offering that answer on StackOverFlow and sharing this code, @Coronel-B! 🙂
Under what license are you releasing this code? You might want to add an
SPDX-License-Identifier: <SPDX License Expression>
line to the class-level KDoc, replacing the<SPDX License Expression>
part with your license of choice. That way, you don't have to add a separate LICENSE file to this gist. See also https://wiki.spdx.org/view/Technical_Team/SPDX_Meta_TagsThanks again!