user485659
user485659

Reputation: 697

scala reflection field class

I'm trying to get the type of an attribute that refers to a custom class, I just get that it's of type Object

My code:

class Edge[N <% Node](var from : N, var to : N) {

  def toXml(c: Class): xml.Elem = {
    <edge>{
      for(field: Field <- classOf[this.type].getDeclaredFields)
        yield <field name={field.name} tpe={field.tpe.toString()}>{ this.getClass().getMethods.find(_.getName() == field.name).get.invoke(this) }</field>
    }</edge>
  }

So the problem here is that I need to switch between the java Field and scala Field: apparently there is no such thing as this.getClass in scala? So I need to go through Java to get the class? However this seems to only result in Objects as types?

Upvotes: 0

Views: 1276

Answers (1)

Matthew Farwell
Matthew Farwell

Reputation: 61695

EDIT: The revised question is: Should scala.reflect.Field or java.lang.reflect.Field be used?

Answer: Always[*] use java.lang.reflect.Field, and in general java reflection for two reasons:

  1. That is what is returned by xxx.getClass().getDeclaredFields()
  2. The following comment is next to the definition of scala.reflect.Field

.

/** This type is required by the compiler and <b>should not be used in client code</b>. */
case class Field(override val fullname: String, tpe: Type) extends GlobalSymbol(fullname)

[*] At least for now. reflection is coming soon to Scala.

-- Original answer:

It would help if you posted the class code as well, but it seems that the field is declared as Object. getType returns the declaration class of the field.

From Field#getType():

Returns a Class object that identifies the declared type for the field represented by this Field object.

class Foo {
  var bar: String = "string"
  var bar2: java.lang.Object = "string"
}

for (field <- new Foo().getClass.getDeclaredFields())  {
   println("field=" + field.getName() + " " + field.getType.toString())
}

gives

field=bar class java.lang.String
field=bar2 class java.lang.Object

If you want the type of the instance, then you will have to do a .getClass() on the instance in the normal way.

Upvotes: 1

Related Questions