Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!