BradCypert.com
Creating a Java Bean from a Scala Class
March 9, 2018

Creating a Java Bean from a Scala Class

Posted on March 9, 2018  (Last modified on December 27, 2022 )
1 minutes  • 171 words
This project uses these versions of languages, frameworks, and libraries.
  • java java : jdk8
  • scala scala : 2.8
This tutorial may work with newer versions and possibly older versions, but has only been tested on the versions mentioned above.

Sometimes, you may find yourself in a situation (like using Scala with Spring) where you need to generate a Java bean but would like to do that in Scala. By default, Scala classes don’t adhere to the requirements of the Bean definition, namely autogenerating getters and setters. Thankfully, there is a BeanProperty decorator that can be used in conjunction with the constructor definition to help adhere to the Bean specification.

You can start using it by importing the BeanProperty like so:

import scala.reflect.BeanProperty

Then in your class definition, you can use the decorator on your member fields to autogenerate the appropriate getters and setters to adhere to the Bean specification.

case class Car(@BeanProperty var color: ColorDefinition,
               @BeanProperty var size: CarSize,
               @BeanProperty var owner: String) {}

Alternatively, you can annotate the class fields instead of the constructor fields.

class Car {
  @BeanProperty var color: ColorDefinition = null
  @BeanProperty var size: CarSize = CarSize.SEDAN
  @BeanProperty var owner: String = null
}

Either of theses styles of applying the decorators will work for you!

Cartoon headshot of Brad Cypert
Follow me

Connect with me to follow along on my journey in my career, open source, and mentorship. Occasionally, I'll share good advice and content (quality not guaranteed).