Reputation: 697
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
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:
.
/** 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