Created
June 5, 2025 18:32
-
-
Save todokr/c849385030146dd77ee4a1aa66b0f47e to your computer and use it in GitHub Desktop.
Learning Hot-reload
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
| package com.example | |
| import java.nio.file.{Files, Path} | |
| class HotLoader(classFilePath: Path, targetClassName: String) extends ClassLoader { | |
| override def findClass(name: String): Class[_] = { | |
| if (name == targetClassName) { | |
| val bytes = Files.readAllBytes(classFilePath) | |
| val clazz = defineClass(name, bytes, 0, bytes.length) | |
| if (clazz == null) { | |
| throw new ClassNotFoundException(s"Class $name not found") | |
| } | |
| println(s"Loaded class: $name") | |
| return clazz | |
| } | |
| super.findClass(name) | |
| } | |
| } |
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
| package com.example | |
| import java.nio.file.{Files, Path, Paths} | |
| object Main { | |
| private val TargetClass = "com.example.TargetClass" | |
| private val ClassFilePath = Paths.get("target/scala-3.3.6/classes/com/example/TargetClass.class").toAbsolutePath | |
| private var LastModified: Long = 0 | |
| def main(args: Array[String]): Unit = | |
| while(true) { | |
| Thread.sleep(5000) | |
| val lastModified = Files.getLastModifiedTime(ClassFilePath).toMillis | |
| if (lastModified != LastModified) { | |
| LastModified = lastModified | |
| println("=" * 50) | |
| println("Change detected") | |
| println("=" * 50) | |
| reload(ClassFilePath) | |
| } | |
| } | |
| private def reload(classFilePath: Path): Unit = { | |
| val hotLoader = new HotLoader(classFilePath, TargetClass) | |
| val clazz = hotLoader.loadClass(TargetClass) | |
| val instance = clazz.getDeclaredConstructor().newInstance() | |
| println(instance) | |
| } | |
| } |
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
| package com.example | |
| class TargetClass { | |
| override def toString: String = "Hello, I am a hot-reloaded class!" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment