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={} tpe={field.tpe.toString()}>{ this.getClass().getMethods.find(_.getName() == }</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?


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())


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.

Category:scala Time:2011-11-10 Views:1

Related post

  • scala reflection error java 2011-11-07

    I'm trying to use scala.reflect to get the class attributes and to write them XML. However I'm getting a strange error def toXml(): xml.Elem = { <node>{ for(field: scala.reflect.Field <- getClass().getDeclaredFields()) { val tmpString = "

  • dynamically map array items to java.reflect.Field objects 2011-03-28

    I need to write code that simulates having a user-defined number of fields available in a class at runtime. The idea being to be able to return java.reflect.Field objects pointing to those "dynamic" fields to client-code. class DynamicFieldClass { /*

  • how to get all instances of a given class/trait with scala reflect? all refs to a given instance? 2013-02-06

    I know it's possible to get the members of a class, and of a given instance, but why is it hard to get all instances of a given class? Doesn't the JVM keep track of the instances of a class? This doesn't work in Java: myInstance.getClass.getInstances

  • Scala Reflection - Loading or finding classes based on trait 2013-07-05

    Does the scala reflection API (2.10) provide any easier means of searching the loaded classes and filtering the list to specific classes which implement a defined trait? ie; trait Widget { def turn(): Int } class Cog extends Widget { def turn() = { 5

  • java.lang.ClassNotFoundException: scala.reflect.api.TypeCreator 2013-12-13

    I'm trying to reflect on a companion object. Using this... import scala.reflect.runtime.{universe => ru} private lazy val universeMirror = ru.runtimeMirror(getClass.getClassLoader) def companion[T, T2](implicit tt: ru.TypeTag[T]): T2 = { val compa

  • Scala reflection with TypeTags and singleton types 2013-12-18

    I've just started experimenting with the reflection API introduced in Scala 2.10 and would expect the code below to evaluate to true five times (REPL). Unfortunately, only the first and last expressions really do. Can somebody explain why this is the

  • scala reflection: getDeclaringTrait? 2009-12-02

    When I research a new library, I sometimes find it hard to locate the implementation of a method. In Java, Metho#getDeclaringClass provides the class that declared a given method. So by iterating over Class#getMethods, I can find for each method, the

  • Is there a way to find the actual class a reflected field was defined in or find a common base class for child objects? 2011-05-17

    I have a field that is defined in a base class and when I use reflection on a child object, I want to retrieve the base class where the field is actually defined. Is there a way to do this in C# .Net 4.0? Alternatively, is there a way to dynamically

  • Java Reflection : internals of java.lang.reflect.Field.getDouble(object) 2011-08-04

    Does anyone know if Field.getDouble(Object) boxes and unboxes a double internally? Thanks, RB --------------Solutions------------- If you use Field.getDouble() on a double field, there is no auto boxing/unboxing. This method existed long before this

  • scala reflection, cast type with asInstanceOf 2011-10-05

    I have trait T class C extends T compiled to .class files. Run scala with -cp <...> to have type T available. Then load class C using reflection: val loader = ScalaClassLoader fromURLs (/* List[URL] */) val anyC = loader.tryToInitializeClass("C

  • Accessing scala object fields from java 2011-10-17

    I'm having trouble accessing the fields of a scala object from java. Scala: object TestObject { val field = 5 } Java: public class JavaTest { public static void main(String[] args) { int i = TestObject.field; } } Error: [error] cannot

  • Scala reflection on object 2011-10-20

    If I have the following scala object: object CustomerState { val PENDING = "pending" val TRIAL = "trial" val PAYING = "paying" val DEACTIVATED_TRIAL = "deactivated_trial" val DEACTIVATED_PAYING = "deactivated_paying" } How can I obtain a list of all

  • How to test if a reflected field's type is, or inherits from, a specified type 2011-12-23

    I am iterating through the FieldInfo of a class. I want to be able to test if a given field is of a certain type. The specific issue is that I want to know all fields that are derived from SortedList. So they are not exactly SortedList, but each one

  • reflect.Field.annotations always null 2012-03-09

    I am trying to play with reflection and annotations. For some reason whenever I add an annotation to a field (or a class or a method), and use reflection to look at the field, I see that its annotations field is null. For example, this code: public c

  • Type from Scala reflection 2011-10-04

    Suppose that I have: trait A class B extends A compiled into class files. Later I load those using reflection: val a = Class forName "A" val b = Class forName "B" Could anyone tell me how to check whether b is the subtype of a? --------------Solution

  • Scala reflection behaves differently on interpreter and compiled code 2011-10-05

    I have trait T class C extends T compiled to .class files. And the piece of code below to load them: val loader = ScalaClassLoader fromURLs (/* List[URL] */) val classB = loader.tryToInitializeClass("B") getOrElse (/* throw something */) println(clas

  • Scala reflection with parameterized types 2011-07-19

    I've written the following function to check whether a given singleton class implements a trait. /** Given a singleton class, returns singleton object if cls implements T. * Else returns None. */ def maybeMakeSingletonObj[T: ClassManifest](cls: Class

  • How to create a decent toString() method in scala using reflection? 2010-01-06

    To make debug-time introspection into classes easy, I'd like to make a generic toString method in the base class for the objects in question. As it's not performance critical code, I'd like to use Reflection to print out field name/value pairs ("x=1,

  • Is there a good reflection library available for Scala? 2010-12-31

    I'm working on a library that needs reflection, and needs Scala-specific information as opposed to what is available via the standard Java reflection API. Right now I'm using the undocumented code in scalap (the Scala equivalent to javap) and trying

Copyright (C), All Rights Reserved.

processed in 0.442 (s). 13 q(s)