mardi 6 janvier 2015

Scala: Printing fields and values of given class

So I wrote Debgug trait that is meant to print fields and values that are stored in class.



class Point(xv: Int, yv: Int) extends Debug {
var x: Int = xv
var y: Int = yv
var a: String = "test"


}



trait Debug{
def debugVars():Any = {
var i = 0
val vars = this.getClass.getDeclaredFields

for(v <- vars){
v.setAccessible(true)
println("Field: " + vars(i).getName() + " => " + vars(i).get())
i+=1
}
}
}

var p : Point = new Point(3,4)
p.debugVars()


The ouptut should be:



Field: x => 3
Field: y => 4
Field: a => test


But compiler (I am using eclipse Luna) throws following error:



java.lang.IllegalArgumentException: Can not set int field Point.x to scala.runtime.BoxedUnit
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(Unknown Source)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.getInt(Unknown Source)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.get(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at Debug$$anonfun$debugVars$1.apply(<console>:21)
at Debug$$anonfun$debugVars$1.apply(<console>:19)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
at Debug$class.debugVars(<console>:19)
at Point.debugVars(<console>:8)
... 53 elided


The problem for me is in the for loop "+vars(i).get()" but I don not have any idea how to repair it. Any solutions or tips?






Aucun commentaire:

Enregistrer un commentaire