Created
February 9, 2010 19:48
-
-
Save p3t0r/299586 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---- 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