juan_gandhi: (VP)
I have a mock db, I want to insert a row in a table; the thing is, id were recently converted from var to val (it was an ancient idea of having variable id, something very weird). Now I had to use reflection, so I did.

         override def insert(o: T): T = {
            val fields = fieldsOf(o.getClass)
            val idField = fields("id")
            idField.set(o, globalID)
            globalID += 1
            update(o)
            o
          }
        }

        private def fieldsOf(clasz: Class[_]):Map[String, Field] = {
          def listFields(c: Class[_]): List[Field] =
            if (c==null) Nil else
              c.getDeclaredFields .filter (!_.getName.contains("$") ) .toList ++ listFields(c.getSuperclass)

          val fields = listFields(clasz)
          fields foreach (_.setAccessible(true))
          fields map (f => f.getName -> f) toMap
        }
juan_gandhi: (VP)
trait TimeReader {
  def currentTime: Long = System.currentTimeMillis
}


...
class DataSomething(val name:String, val number:Long...) extends TimeReader {...}


...
val sut = new DataSomething("Ivanov", 42,...) with MockTime

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

June 2025

S M T W T F S
1 2345 6 7
8 9 10 11 121314
15161718 1920 21
222324252627 28
29 30     

Syndicate

RSS Atom

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 3rd, 2025 08:04 am
Powered by Dreamwidth Studios