dimanche 4 septembre 2022

Hot to lookup properties with annotation in subclasses of abstract class?

I have an abstract class with 2 subclasses. I have an annotation on some of the subclasses fields.

I want to create a function which can take the abstract class as argument, iterate over all the fields of the subclasses and replace every field with the annontation with something else (empty string in the below example).

For example:

@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class PersonalData

abstract class SomeAbstractClass(open val name: String)

class Foo(override val name: String, @PersonalData val dateOfBirth: String): SomeAbstractClass(name)

class Bar(override val name: String, val notPersonal: String): SomeAbstractClass(name)

fun getObjWithoutPersonalData(abstractClass: SomeAbstractClass) : SomeAbstractClass {
   // todo - iterate over all fields and replace every field the has @PersonalData annotation with empty string. return the updated object
}

I know it should be done using reflection I just wasn't able to understand exactly how. Would appreciate any help :)





Aucun commentaire:

Enregistrer un commentaire