Creating Scala JavaBeans with the @BeanProperty annotation

Scala JavaBean FAQ: How do I create the Scala equivalent of a JavaBean in Java (a Scala JavaBean)?

There are times when you're working with Scala where backwards compatibility with Java and JavaBeans is required. I ran into this recently with the Java Snakeyaml library (see my Scala YAML parsing with Snakeyaml tutorial).

By default Scala doesn't generate JavaBeans for your Scala classes, which is to say that the 'get' and 'set' methods aren't created automatically for you, and Scala doesn't follow the JavaBean specification.

That being said, you can create Scala classes that do follow the JavaBean specification, using the Scala BeanProperty annotation, as shown in the following examples. First, here's a small Scala class, where I use the BeanProperty annotation on the class properties/fields in the class constructor:

class Person(@BeanProperty var firstName: String, 
             @BeanProperty var lastName: String, 
             @BeanProperty var age: Int) {
  override def toString: String = return format("%s, %s, %d", firstName, lastName, age)

This is pretty cool; just by adding the @BeanProperty tag to your class fields, the get and set (getter and setter) JavaBean methods will be generated for you automatically.

Scala JavaBean example #2

Next up, here's a larger Scala class, where I use the @BeanProperty annotation on the class fields, but this time not in the class constructor:

class EmailAccount {
    @BeanProperty var accountName: String = null
    @BeanProperty var username: String = null
    @BeanProperty var password: String = null
    @BeanProperty var mailbox: String = null
    @BeanProperty var imapServerUrl: String = null
    @BeanProperty var minutesBetweenChecks: Int = 0
    @BeanProperty var protocol: String = null
    @BeanProperty var usersOfInterest = new java.util.ArrayList[String]()

Despite the slightly different way of creating these classes, once again, the getters and setters are created for me.

I'll leave you with these examples, but if you want to know more about why I needed to use this "Scala JavaBean" approach, and how I used them in my application, I'll again refer you to my Scala YAML parsing tutorial.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.