1

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 = "<" + field.name + ">" + this.getClass().getMethods.find(_.getName == field.name).get.invoke(this) + "</" + field.name + ">"
    print(tmpString)
  }
 }</node>
}

The error:

error: type mismatch;
found   : scala.reflect.Field => Unit
required: java.lang.reflect.Field => ?
for(field: scala.reflect.Field <- getClass().getDeclaredFields()) {

So even if I explicitly use scala.reflect.Field, it still is viewed as java.lang.reflect.Field?

1 Answer 1

7

getClass().getDeclaredFields() returns java.lang.reflect.Field objects. Unless you find a way to convert between these two classes, you cannot declare them as scala.reflect.Field and expect them to work.

EDIT: fix for your code:

for(field: java.lang.reflect.Field <- getClass().getDeclaredFields()) {
Sign up to request clarification or add additional context in comments.

3 Comments

is there any way to get the list of class fields in scala?
@user485659, see the edit. Keep in mind that in a lot of cases, you don't even need to declare the type, as it will be inferred.
Thanks, however I'm facing another issue here now, 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: <edge>{ for(field: java.lang.reflect.Field <- getClass().getDeclaredFields()) yield <field name={field.getName()} tpe={field.getType().toString()}>{ this.getClass().getMethods.find(_.getName == field.getName()).get.invoke(this) }</field> }</edge>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.