Last active
January 18, 2025 17:36
-
-
Save akjir/4616615 to your computer and use it in GitHub Desktop.
Access private fields and methods using Java Reflection in Scala.
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
object Main extends App { | |
val printer = new Printer[String]() | |
val break = true | |
val text = "access granted" | |
//cannot be accessed: | |
//printer.printCodeName | |
//printer.codeName = "Rejewski" | |
//printer.printCodeName | |
//printer.printItem(text, break) | |
val printerClass = classOf[Printer[String]] | |
val method1 = printerClass.getDeclaredMethod("printCodeName") // no parameters | |
method1.setAccessible(true) | |
method1.invoke(printer) | |
val field = printerClass.getDeclaredField("codeName") | |
field.setAccessible(true) | |
field.set(printer, "Rejewski") | |
method1.invoke(printer) | |
val method2 = printerClass.getDeclaredMethod("printItem", classOf[Object], classOf[Boolean]) // Type T is object | |
method2.setAccessible(true) | |
method2.invoke(printer, text.asInstanceOf[Object], break.asInstanceOf[Object]) | |
//output: | |
//Scherbius | |
//Rejewski | |
//access granted | |
} | |
class Printer[T] { | |
private[this] var codeName = "Scherbius" | |
private def printCodeName = println(codeName) | |
protected def printItem(item: T, break: Boolean) = if (break) println(item) else print(item) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment