Fields which satisfy JavaBean specification – BeanProperties in Scala

We have seen previously about declaring fields in classes in Scala and also saw the kind of bytecode created for each of the cases. But lot of Java tools out there expect the fields in classes to follow the JavaBeans specification and in order to support that Scala provides @BeanProperty annotation.

also read:

BeanProperties in Scala

Let’s have a look at some code:

import scala.reflect.BeanProperty
class Book{
  @BeanProperty var title:String = _
  @BeanProperty val isbn:String = "ISBN10"
}

Let’s compile the above code and use javap to inspect the bytecode.

$ scalac Book.scala
$ javap Book.class
Compiled from "Book.scala"
public class Book implements scala.ScalaObject {
  public java.lang.String title();
  public void title_$eq(java.lang.String);
  public void setTitle(java.lang.String);
  public java.lang.String isbn();
  public java.lang.String getIsbn();
  public java.lang.String getTitle();
  public Book();
}

The field which was declared with var keyword would have a getField and setField generated where as the field declared with val keyword would have only a getField generated. We already know from here the difference between val and var.

In the above example, title is declared as var and isbn is declared as val. Hence there are getters and setters assocaited with title field and only getter associated with the isbn field.

Comments

comments

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Speak Your Mind

*