All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mercateo.jsonschema.property.FieldCollector.kt Maven / Gradle / Ivy

There is a newer version: 0.2.0
Show newest version
package com.mercateo.jsonschema.property

import com.mercateo.jsonschema.generictype.GenericType
import com.mercateo.jsonschema.property.annotation.AnnotationProcessor
import java.lang.reflect.Field
import java.lang.reflect.Modifier

class FieldCollector(
        private val config: FieldCollectorConfig = FieldCollectorConfig(),
        private val annotationProcessor: AnnotationProcessor = AnnotationProcessor()
) : RawPropertyCollector {

    override fun  forType(genericType: GenericType): Sequence> {
        return sequenceOf(*genericType.declaredFields)
                .filter { !it.isSynthetic }
                .filter { !Modifier.isStatic(it.modifiers) }
                .filter { config.includePrivateFields || Modifier.isPublic(it.modifiers) }
                .map { mapRawDataProperty(it, genericType) }
    }

    private fun  mapRawDataProperty(field: Field, genericType: GenericType): RawProperty {
        val fieldType = GenericType.ofField(field, genericType.type)

        return RawProperty(field.name,
                fieldType,
                annotationProcessor.collectAndGroup(*field.annotations),
                { instance: S -> valueAccessor(field, instance)})
    }

    private fun  valueAccessor(field: Field, instance: S): Any? {
        if (config.includePrivateFields) {
            field.isAccessible = true
        }
        return field.get(instance)
    }
}