Skip to content

Instantly share code, notes, and snippets.

@p3t0r
Created February 9, 2010 19:48
Show Gist options
  • Save p3t0r/299586 to your computer and use it in GitHub Desktop.
Save p3t0r/299586 to your computer and use it in GitHub Desktop.
// ---- Implementation
import java.beans.Introspector
object BeanUtils {
val pathSeperator = """\."""
def readValue(obj: Object, path: String): String = {
val res = path.split(pathSeperator).foldLeft(obj) {
(a: Object, prop: String) =>
val sourceInfo = Introspector.getBeanInfo(a.getClass)
val sourceDescriptors = sourceInfo.getPropertyDescriptors()
val propertyDescriptor = sourceDescriptors.find(_.getName == prop).get
propertyDescriptor.getReadMethod.invoke(a)
}
res.toString
}
}
// ---- TESTCODE
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.{FlatSpec}
class BeanUtilsSpec extends FlatSpec with ShouldMatchers {
"BeanUtils" should "return a simple bean property as a string" in {
BeanUtils.readValue(new Person("peter", null), "name") should equal("peter")
}
"BeanUtils" should "be capable of traversing a path" in {
BeanUtils.readValue(new Person("peter", new Address("bellstraat", "hilversum")), "address.street") should equal("bellstraat")
}
"BeanUtils" should "throw a NoSuchElementException exception when a non-existing property is referenced" in {
intercept[NoSuchElementException] {
BeanUtils.readValue(new Person("peter", null), "apple")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment