Sohaib
Sohaib

Reputation: 4694

Scala dynamically access a field in a class

Consider a class with lots of values

class Test {
    val a1 = "test1"
    val a2 = "test2"
    ..
    ..
    val a25 = "test25"
}

Can a function like this be written to access the nth variable.

def getVar(n: Int, test: Test) = {
    test.("test"+n) //something like this to access the nth variable
}

I know this can be done with a collection but my question is can this type of reflection be done.

Upvotes: 2

Views: 1878

Answers (2)

余杰水
余杰水

Reputation: 1384

use Dynamic

import scala.Dynamic
import scala.language.dynamics

object Test extends Dynamic {
  val a1 = "test1"
  val a2 = "test2"
  val a3 = "test3"
  val list = List(a1, a2, a3)

  def selectDynamic(s: String) = {
    list(s.replace("test", "").toInt-1)
  }
}

assert(Test.list(1) == Test.test2)

Upvotes: 1

Johny T Koshy
Johny T Koshy

Reputation: 3887

val field = test.getClass.getDeclaredFields.apply(n)
field.setAccessible(true)
field.get(test)

Upvotes: 5

Related Questions