mardi 21 avril 2015

Scala Reflection : why getMethods can return the val members?

In Scala, I have an Abstract Class:

abstract class AbstractSQLParser {

  def apply(input: String): Int = {

    println(reserveWords)
    return 1
  }

  protected case class Keyword(str: String)
  // use Reflection here
  protected lazy val reserveWords: Int =
      this.getClass
          .getMethods
          .filter(_.getReturnType == classOf[Keyword])
          .length
}

and another extends it :

class SqlParserDemo extends AbstractSQLParser{

  def apply(input: String, onError: Boolean) : Int = {

    apply(input)
  }

  protected val CREATE = Keyword("CREATE")
  protected val TEMPORARY = Keyword("TEMPORARY")
  protected val TABLE = Keyword("TABLE")
  protected val IF = Keyword("IF")
  protected val NOT = Keyword("NOT")
  protected val EXISTS = Keyword("EXISTS")

  def func1 = Keyword("HI")
}

but when I call

val sqlParser = new SqlParserDemo
print(sqlParser.apply("hello", false))

the output is :

7

1

What confuses me is : why getMethods can return the val members ?

You see, in the sub-class, I have six val , and one function.

In Oracle doc,

public Method[] getMethods() throws SecurityException Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces

Aucun commentaire:

Enregistrer un commentaire