Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda