About reassignment by activej-codegen #297
Answered
by
eduard-vasinskyi
zhangtianxiao
asked this question in
Q&A
Replies: 2 comments 2 replies
-
package org.feather
import io.activej.codegen.ClassBuilder
import io.activej.codegen.DefiningClassLoader
import io.activej.codegen.expression.Expressions
import io.activej.codegen.expression.Expressions.cast
import java.io.File
import java.lang.reflect.Method
import java.util.function.Function
private val classLoader = DefiningClassLoader.create()
private fun makeCall2(o: Any, method: Method): CCall {
val cb = ClassBuilder.create(CCall::class.java)
cb.withMethod("invoke",
Expressions.let(cast(Expressions.arg(0), Array::class.java)) { arr ->
Expressions.call(
cast(Expressions.call(Expressions.self(), "getO"), method.declaringClass),
method.name,
*(method.parameterTypes.mapIndexed { index, it ->
Expressions.arrayGet(arr, Expressions.value(index))
}.toTypedArray())
)
}
)
val bytecode = cb.toBytecode(classLoader)
val f = File("target/classes", bytecode.className.replace(".", "/") + ".class")
val p = f.parentFile
if (!p.exists()) p.mkdirs()
f.writeBytes(bytecode.bytecode)
val c = bytecode.defineClass(classLoader) as Class<CCall>
println(c.canonicalName)
val cc = c.getDeclaredConstructor().newInstance()
cc.o = o
return cc
}
abstract class CCall : Function<Array<*>, Any?> {
lateinit var o: Any
abstract operator fun invoke(vararg args: Any?): Any?
}
fun main() {
val fn = makeCall2("123", String::class.java.getDeclaredMethod("length"))
println(fn(arrayOf(0)))
val fn2 = makeCall2(listOf(1, 2, 3), List::class.java.getDeclaredMethod("size"))
println(fn2(arrayOf(0)))
} The generated bytecode will contain the new instruction, like: public final class CCall_2 extends CCall {
public static Void $GENERATED;
public CCall_2() {
}
public final Object invoke(Object[] var1) {
// ???
return new Integer(((List)this.getO()).size());
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
-
Hi, @zhangtianxiao cb2.withMethod("apply", let(cast(arg(0), int[].class),
array -> let(value(0), v -> sequence(
iterateArray(array, it -> set(v, add(v, it))),
v
)))); I didn't quite get the other code snippets. What is the problem there? |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
zhangtianxiao
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
thanks!
Beta Was this translation helpful? Give feedback.
All reactions