Skip to content

Instantly share code, notes, and snippets.

@lenalebt
Created March 25, 2024 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lenalebt/d8d75e398c49dad256e4a0c005ab9a15 to your computer and use it in GitHub Desktop.
Save lenalebt/d8d75e398c49dad256e4a0c005ab9a15 to your computer and use it in GitHub Desktop.
kotlin support for google guice
package com.google.inject
import com.google.inject.internal.Errors
import com.google.inject.internal.KotlinSupportInterface
import java.lang.reflect.Constructor
import java.lang.reflect.Field
import java.lang.reflect.Method
import java.util.function.Predicate
import kotlin.reflect.full.declaredFunctions
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.jvmErasure
class KotlinSupportImpl : KotlinSupportInterface {
companion object {
@JvmField
val INSTANCE = KotlinSupportImpl()
}
override fun getAnnotations(field: Field?): Array<Annotation> {
if (field == null) {
return emptyArray()
}
field.declaringClass.kotlin.declaredMemberProperties.forEach {
if (it.name == field.name) {
return it.annotations.toTypedArray()
}
}
return emptyArray()
}
override fun isNullable(field: Field?): Boolean {
if (field != null) {
field.declaringClass.kotlin.declaredMemberProperties.forEach {
if (it.name == field.name) {
return it.returnType.isMarkedNullable
}
}
return false
} else {
return false
}
}
override fun getIsParameterKotlinNullablePredicate(constructor: Constructor<*>?): Predicate<Int> {
if (constructor == null) {
return Predicate { false }
}
constructor.declaringClass.kotlin.constructors.forEach {
if (it.parameters.zip(constructor.parameters).all { (kotlinParam, javaParam) -> kotlinParam.type.jvmErasure.java == javaParam.type }) {
return Predicate { index -> it.parameters[index].type.isMarkedNullable }
}
}
return Predicate { false }
}
override fun getIsParameterKotlinNullablePredicate(method: Method?): Predicate<Int> {
if (method == null) {
return Predicate { false }
}
method.declaringClass.kotlin.declaredFunctions.forEach {
if (it.name == method.name &&
it.parameters.zip(method.parameters).all { (kotlinParam, javaParam) -> kotlinParam.type.jvmErasure.java == javaParam.type }) {
return Predicate { index -> it.returnType.isMarkedNullable }
}
}
return Predicate { false }
}
override fun checkConstructorParameterAnnotations(constructor: Constructor<*>?, errors: Errors?) {
if (constructor == null) {
return
}
// do nothing, I have no clue what might actually be bad
return
}
override fun isLocalClass(clazz: Class<*>?): Boolean {
return clazz != null && clazz.kotlin.isInner
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment