GetBeanProperties via Scala


一个简单的用Scala写的获取bean属性的例子。核心方法是Introspector#getBean(Class)

import java.beans.Introspector

object GetBeanProperties {

  class Person(id: Long, name: String) {
    def getId = id
    def getName = name
  }

  def main(args: Array[String]): Unit = {
    println(GetBeanProperties(null))
    println(GetBeanProperties(new Person(1L, "xnnyygn")))
  }
  
  def apply[T](bean: T): Map[String, Any] =  Option(bean) match {
    case None => Map[String, Any]()
    case _ => doApply(bean)
  }
  
  private def doApply[T](bean: T): Map[String, Any] = {
    Introspector.getBeanInfo(bean.getClass).getPropertyDescriptors.flatMap { d =>
      Option(d.getReadMethod).map(getter => (d.getName, getter.invoke(bean)))
    }.toMap - "class"
  }
  
}