reflection - Scala: set a field value reflectively from field name -


I am learning Scala and can not find out how:

I use Scala Objects and Google There is a mapper between the appenzin entities, so if I have such a class:

  class student {var id: long var name: string}  
< P> I need to make an example of that square, in Java, I'll get the field by its name and then field.set (value, value) but I do not know that Areas to look at scala.

I can not use Java's reflection because the area of ​​the student is seen as private and field. The set throws an error due to that reason.

Thanks

Scala gets converted into a private area, an eater and a setter is. So by using a string to identify / set it to get a var, you have to use the Java Reflection to find the gateter / setter methods. Below is a code snippet that does this, please note that this code runs under Scala 2.8.0 and there is no existence by the name and errors of the duplicated method.

class student {var id: long = _ var name: string = _} implicit def reflector (ref: AnyRef) = new {def getV (name: string): any = ref GetClass.getMethods.find (_ getName == name) .get.invoke (ref) def setV (name: string, value: any): unit = ref.getClass.getMethods.find (_.getName == name + " _ $ Eq "). Get.invoke (ref, value.exestance [anyRef]) val s = new student s.setV ("(" Id ", 1234) println (s.getV (" id ")) print / print" 1234 " "Walter" s.setV ("id", 1234) "
println (s.getV (" name "))

Comments

Popular posts from this blog

MySql variables and php -

url rewriting - How to implement the returnurl like SO in PHP? -

Which Python client library should I use for CouchdB? -