'Creating Scala JavaBeans with the @BeanProperty annotation'에 해당되는 글 1건

  1. 2014.03.28 Creating Scala JavaBeans with the @BeanProperty annotation
00.scala2014. 3. 28. 12:59
반응형

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 ScalaBeanProperty 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.

Posted by 1010