Created
February 22, 2024 17:21
-
-
Save duangsuse/d022c7ad037bb7fed446f72ec9b38ef7 to your computer and use it in GitHub Desktop.
dumps(Pair::class) (Pair(0,0), mutableMapOf("first" to 3))
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jdk.jshell.JShell | |
import jdk.jshell.spi.* | |
import java.lang.reflect.* | |
import kotlin.reflect.KClass | |
import kotlin.reflect.full.memberProperties | |
//dumps(Pair::class) (Pair(0,0), mutableMapOf("first" to 3)) | |
fun dumps(T:KClass<*>, ld:T=JS("(void)(${T} o, java.util.Map<String,Object> m){"+ | |
T.memberProperties.joinToString(""){" m.put(\"${it.name}\",o.get${it.name.capitalize()}());"}+"}")!! | |
)=fun(o:Any, m:Map<*,*>)=ld.main(o,m).let{m} | |
typealias T=Class<*> | |
fun T.main(vararg a:Any?)=methods[0].run{setAccessible(true);invoke(null,*a)} | |
inline fun <reified T> SAM(fu: String, noinline fn: (Array<Any>) -> Any?)=java.lang.reflect.Proxy.newProxyInstance( | |
T::class.java.classLoader, arrayOf(T::class.java) | |
) { o,f, args -> if (f.name == fu) fn(args) else null } as T | |
var JS: (String) -> T? = run { | |
val cl = object : ClassLoader() { | |
var T: T? = null; var i=0 | |
fun defineClass(name: String, b: ByteArray)=super.defineClass(name, b, 0, b.size).also { T = it } | |
override fun findClass(name:String)=Class.forName(name) | |
} | |
val loader = SAM<ExecutionControl>("load") { x -> | |
for (it in x[0] as Array<ExecutionControl.ClassBytecodes>) cl.defineClass(it.name(), it.bytecodes()) | |
null | |
} | |
val js = JShell.builder().executionEngine(SAM<ExecutionControlProvider>("generate") { loader }, null).build() | |
fun fnID(s:String)=if(s[0]=='(')cl.run{ val rp=s.indexOf(')'); i=i+1;"${s.substring(1,rp)} f${i}${s.substring(rp+1)}".replace("class ","") }else s | |
{ s -> try{js.eval(fnID(s))}catch(_:Exception){}; cl.T } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment