Last active
February 8, 2022 17:53
-
-
Save vsuharnikov/336944205ff095e520f775eff0d03b6d to your computer and use it in GitHub Desktop.
javap for Ammonite REPL
This file contains 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
// ~/.ammonite/predef.sc | |
// Works on Scala 3, easy to adapt to Scala2 | |
// Make sure: | |
// 1. You run Ammonite for Scala 3: 3.1-2.5.2+ (see https://github.com/com-lihaoyi/Ammonite/releases ) | |
// 2. You provide required JVM exports: | |
// JAVA_OPTS="--add-exports=jdk.jdeps/com.sun.tools.javap=ALL-UNNAMED" ~/Downloads/3.1-2.5.2 | |
import java.io.{File, FileOutputStream} | |
import scala.util.Using | |
import scala.reflect.ClassTag | |
// Works only in Scala 3+ | |
def javapWithOptions[T <: AnyRef](options: Array[String])(using ct: ClassTag[T]): Unit = { | |
val targetFile = File.createTempFile("javap", "repl.class") | |
Using(ct.runtimeClass.getClassLoader.getResourceAsStream(ct.runtimeClass.getName.replace('.', '/') + ".class")) { classStream => | |
Using(new FileOutputStream(targetFile)) { outStream => | |
classStream.transferTo(outStream) | |
outStream.flush() | |
} | |
} | |
val task = new com.sun.tools.javap.JavapTask | |
// Doesn't work without this line in Ammonite, but works in scala REPL ¯\_(ツ)_/¯ | |
scala.util.Try(task.handleOptions(Array("-cp", "Dog"))) | |
task.handleOptions(Array(targetFile.getAbsolutePath)) | |
task.handleOptions(Array("-c", "-p")) | |
task.run() | |
} | |
def javap[T <: AnyRef: ClassTag]: Unit = javapWithOptions[T](Array.empty) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment