I am making a library, In one of the functionality, I receive an object and I have to perform an operation on fields and save them on a Map. The object can have a field of type custom class which will again have fields and in that case, I'll need a nested hashmap. To do that I'll need to call my function recursively if the type of field in a custom class.
Now the problem is, how will I check if the type of field is a custom class or not, right now I am doing it by package name but have to make it general
private fun getAllFields(`object`: Any): MutableMap<String, Any> {
val map: MutableMap<String, Any> = HashMap()
val internalMap: MutableMap<String, Any> = HashMap()
for (field in `object`::class.java.declaredFields.toMutableList()) {
field.isAccessible = true
if (field.type.name.contains("com.example")) {
internalMap.putAll(getAllFields(field.get(`object`)))
}
As you're using reflection, you could introduce an annotation:
package org.your.library
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class YourCoolAnnotation
Which then can be used by the users of your library to annotate the classes that they want to be nested:
package com.example.libraryuser
@YourCoolAnnotation
class MyCustomClass
Then you can replace your:
if (field.type.name.contains("com.example")) {
With:
if (field.type.isAnnotationPresent(YourCoolAnnotation::class.java)) {
You could also specify the annotation to be only used on fields which would make this a lot more dynamic:
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class YourCoolAnnotation
and then check if the field has the annotation and not the type itself:
if (field.isAnnotationPresent(YourCoolAnnotation::class.java)) {