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

com.itangcent.intellij.context.ThreadLocalContextBeanProxies.kt Maven / Gradle / Ivy

Go to download

Help for developing plugins for JetBrains products. KotlinAnAction:provide ActionContext(support inject guice) for actionPerformed

The newest version!
package com.itangcent.intellij.context

import com.itangcent.intellij.constant.EventKey
import java.lang.ref.WeakReference
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import kotlin.reflect.KClass
import kotlin.reflect.full.cast


object ThreadLocalContextBeanProxies {

    /**
     * clazz should be interface
     */
    fun  instance(clazz: KClass): T {
        val loader = clazz.java.classLoader
        val interfaces = arrayOf(clazz.java)
        return clazz.cast(
            Proxy.newProxyInstance(
                loader, interfaces,
                LazyInitInvocationHandler(clazz)
            )
        )
    }

    class LazyInitInvocationHandler(private var clazz: KClass) : InvocationHandler {

        private var localCache: ThreadLocal> = ThreadLocal()

        private val localBean: T?
            get() {
                var weakCacheBean = localCache.get()
                var cacheBean: T?
                if (weakCacheBean != null) {
                    cacheBean = weakCacheBean.get()
                    if (cacheBean != null) {
                        return cacheBean
                    }
                }

                val actionContext = ActionContext.getContext()
                cacheBean = actionContext!!.instance(clazz)
                weakCacheBean = WeakReference(cacheBean)
                localCache.set(weakCacheBean)
                actionContext.on(EventKey.ON_COMPLETED) {
                    weakCacheBean.clear()
                }

                return cacheBean
            }


        override fun invoke(proxy: Any?, method: Method?, args: Array?): Any? {
            return when (args) {
                null -> method!!.invoke(localBean)
                else -> method!!.invoke(localBean, *args)
            }
        }

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy