Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
Identify Custom Class in Kotlin

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`)))
        }
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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)) {
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda