Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This REPL session shows how you can invoke the setter with the Scala Reflection API:</p> <pre><code>scala&gt; import scala.reflect.runtime. { universe =&gt; ru } import scala.reflect.runtime.{universe=&gt;ru} scala&gt; trait TO { var age: Int = _ } defined trait TO scala&gt; class UMTInnerTO extends TO defined class UMTInnerTO scala&gt; val inner = new UMTInnerTO inner: UMTInnerTO = UMTInnerTO@173379f scala&gt; val m = ru.runtimeMirror(inner.getClass.getClassLoader) m: reflect.runtime.universe.Mirror ... scala&gt; val im = m.reflect(inner) im: reflect.runtime.universe.InstanceMirror = instance mirror for UMTInnerTO@173379f scala&gt; val setterSymb = (ru.typeOf[UMTInnerTO].members find (_.name.decoded == "age_=")).get setterSymb: reflect.runtime.universe.Symbol = method age_= scala&gt; val setter = im.reflectMethod(setterSymb.asMethod) setter: reflect.runtime.universe.MethodMirror = method mirror for TO.age_$eq(x$1: scala.Int): scala.Unit (bound to UMTInnerTO@173379f) scala&gt; inner.age res0: Int = 0 scala&gt; setter(5) res1: Any = () scala&gt; inner.age res2: Int = 5 </code></pre> <p>You may visit the <a href="http://docs.scala-lang.org/overviews/reflection/overview.html" rel="nofollow">Scala Reflection Documentation</a> to understand what is happening in the snippet.</p> <p>--</p> <p><strong>UPDATED</strong>: Anyway, if you are still interested in the Java API, here we go!</p> <p>You should be aware of <em>setters</em> in Scala don't use the Java naming convention. You won't find a <code>setAge</code> method (at least, if you don't declare it manually). Instead you have to search for an <code>age_=</code> method.</p> <pre><code>scala&gt; classOf[UMTInnerTO].getMethod("age_$eq", classOf[Int]) res0: java.lang.reflect.Method = public void UMTInnerTO.age_$eq(int) scala&gt; inner.age res1: Int = 0 scala&gt; res0.invoke(inner, 3: Integer) res2: Object = null scala&gt; inner.age res3: Int = 3 </code></pre> <p>This <a href="http://dustinmartin.net/getters-and-setters-in-scala/" rel="nofollow">post</a> on getters and setters could be helpful.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload