mardi 18 juillet 2017

Can not access private field via reflection in scala

I try to access the private field of a class, but hit the NoSuchFieldException. Here's the code, I can access the private field of class Printer, but could not access the private field of SparkContext. I am sure SparkContext has this field, here's source code of SparkContext. http://ift.tt/2aY2Q44

object SparkExample extends App {

  val printer = new Printer[String]()
  val break = true
  val text = "access granted"


  val field = classOf[Printer[String]].getDeclaredField("codeName")
  field.setAccessible(true)
  field.set(printer, "Rejewski")

  val sparkClass = classOf[SparkContext]
  val field2 = sparkClass.getDeclaredField("_conf")
  field2.setAccessible(true)


}

class Printer[T] {

  private var codeName = "Scherbius"

  private def printCodeName = println(codeName)

  protected def printItem(item: T, break: Boolean) = if (break) println(item) else print(item)

}

Exception I get

Exception in thread "main" java.lang.NoSuchFieldException: _conf
    at java.lang.Class.getDeclaredField(Class.java:2070)
    at com.zjffdu.tutorial.spark.SparkExample$delayedInit$body.apply(SparkExample.scala:19)
    at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App$$anonfun$main$1.apply(App.scala:71)
    at scala.App$$anonfun$main$1.apply(App.scala:71)
    at scala.collection.immutable.List.foreach(List.scala:318)
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:32)
    at scala.App$class.main(App.scala:71)
    at com.zjffdu.tutorial.spark.SparkExample$.main(SparkExample.scala:7)
    at com.zjffdu.tutorial.spark.SparkExample.main(SparkExample.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)





Aucun commentaire:

Enregistrer un commentaire