|
| 1 | +package com.fasterxml.jackson.module.kotlin |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.DeserializationContext |
| 4 | +import com.fasterxml.jackson.databind.MapperFeature |
| 5 | +import com.fasterxml.jackson.databind.introspect.AnnotatedConstructor |
| 6 | +import com.fasterxml.jackson.databind.introspect.AnnotatedMethod |
| 7 | +import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams |
| 8 | +import java.lang.reflect.Constructor |
| 9 | +import java.lang.reflect.Method |
| 10 | +import kotlin.reflect.KFunction |
| 11 | +import kotlin.reflect.KParameter |
| 12 | +import kotlin.reflect.full.valueParameters |
| 13 | + |
| 14 | +/** |
| 15 | + * A class that abstracts the creation of instances by calling KFunction. |
| 16 | + * @see KotlinValueInstantiator |
| 17 | + */ |
| 18 | +internal sealed class ValueCreator<T> { |
| 19 | + /** |
| 20 | + * Function to be call. |
| 21 | + */ |
| 22 | + protected abstract val callable: KFunction<T> |
| 23 | + |
| 24 | + /** |
| 25 | + * Initial value for accessibility by reflection. |
| 26 | + */ |
| 27 | + protected abstract val accessible: Boolean |
| 28 | + |
| 29 | + /** |
| 30 | + * ValueParameters of the KFunction to be called. |
| 31 | + */ |
| 32 | + val valueParameters: List<KParameter> by lazy { callable.valueParameters } |
| 33 | + |
| 34 | + /** |
| 35 | + * Checking process to see if access from context is possible. |
| 36 | + * @throws IllegalAccessException |
| 37 | + */ |
| 38 | + fun checkAccessibility(ctxt: DeserializationContext) { |
| 39 | + if ((!accessible && ctxt.config.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) || |
| 40 | + (accessible && ctxt.config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS))) { |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + throw IllegalAccessException("Cannot access to function or companion object instance, target: $callable") |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Function call with default values enabled. |
| 49 | + */ |
| 50 | + fun callBy(args: Map<KParameter, Any?>): T = callable.callBy(args) |
| 51 | + |
| 52 | + companion object { |
| 53 | + @Suppress("UNCHECKED_CAST") |
| 54 | + fun of( |
| 55 | + _withArgsCreator: AnnotatedWithParams, cache: ReflectionCache |
| 56 | + ): ValueCreator<*>? = when (_withArgsCreator) { |
| 57 | + is AnnotatedConstructor -> cache.kotlinFromJava(_withArgsCreator.annotated as Constructor<Any>) |
| 58 | + ?.let { ConstructorValueCreator(it) } |
| 59 | + is AnnotatedMethod -> cache.kotlinFromJava(_withArgsCreator.annotated as Method) |
| 60 | + ?.let { MethodValueCreator.of(it) } |
| 61 | + else -> throw IllegalStateException("Expected a constructor or method to create a Kotlin object, instead found ${_withArgsCreator.annotated.javaClass.name}") |
| 62 | + } // we cannot reflect this method so do the default Java-ish behavior |
| 63 | + } |
| 64 | +} |
0 commit comments