簡単な例を書いてみました
このようなJavaクラスがあるとします
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world");
}
}
次に、それをバイト配列に変換するためのスカラ コードを記述します。
import java.io.{FileInputStream, FileOutputStream}
import collection.mutable.ArrayBuffer
val in = new FileInputStream("HelloWorld.class")
val out = new FileOutputStream("HelloWorldBytes.scala")
Console.withOut(out) {
var data = in.read()
print("val helloWorldBytes = Array[Byte](")
print(if(data < 128) data else data - 256)
data = in.read()
while(data >= 0) {
print(", ")
print(if(data < 128) data else data - 256)
data = in.read()
}
println(")")
}
in.close()
out.close()
そして、あなたはこのようにそれを使うことができます
val helloWorldBytes = Array[Byte](...)
object Loader extends ClassLoader {
override
def findClass(name: String): Class[_] =
if(name == "HelloWorld") defineClass(name, helloWorldBytes, 0, helloWorldBytes.size)
else super.findClass(name)
}
val helloWorld = Loader.loadClass("HelloWorld")
helloWorld.getDeclaredMethod("main", classOf[Array[String]]).invoke(null,null)