mirror of
https://github.com/GTNewHorizons/Forgelin.git
synced 2026-10-26 14:24:03 +00:00
Read Kotlin object instances without kotlin-reflect
This commit is contained in:
1 parent
f346204b8f
commit
304b810c03
1 file changed
+16
-1
@@ -7,6 +7,7 @@ import cpw.mods.fml.relauncher.Side
|
||||
import org.apache.logging.log4j.LogManager
|
||||
import java.lang.reflect.Field
|
||||
import java.lang.reflect.Method
|
||||
import java.lang.reflect.Modifier
|
||||
|
||||
/**
|
||||
* Forge {@link ILanguageAdapter} for Kotlin
|
||||
@@ -31,7 +32,21 @@ class KotlinAdapter : ILanguageAdapter {
|
||||
|
||||
override fun getNewInstance(container: FMLModContainer, objectClass: Class<*>, classLoader: ClassLoader, factoryMarkedAnnotation: Method?): Any {
|
||||
log.debug("FML has asked for ${objectClass.simpleName} to be constructed")
|
||||
return objectClass.kotlin.objectInstance ?: objectClass.newInstance()
|
||||
return declaredObjectInstance(objectClass) ?: objectClass.kotlin.objectInstance ?: objectClass.newInstance()
|
||||
}
|
||||
|
||||
// A Kotlin object is a class with a static INSTANCE of itself and no public constructor. Reading that field
|
||||
// directly saves starting up kotlin-reflect just to find it.
|
||||
private fun declaredObjectInstance(objectClass: Class<*>): Any? {
|
||||
val field = try {
|
||||
objectClass.getDeclaredField("INSTANCE")
|
||||
} catch (e: NoSuchFieldException) {
|
||||
return null
|
||||
}
|
||||
if (field.type != objectClass || !Modifier.isStatic(field.modifiers)) return null
|
||||
if (objectClass.declaredConstructors.any { Modifier.isPublic(it.modifiers) }) return null
|
||||
field.isAccessible = true
|
||||
return field.get(null)
|
||||
}
|
||||
|
||||
override fun setInternalProxies(mod: ModContainer?, side: Side?, loader: ClassLoader?) {
|
||||
|
||||
Reference in new issue
Block a user