Bean properties
BeanIntrospector builds properties from JavaBean getters and setters, with the field of the same name when there is one.
Model
get, is and set
Every method named getX or isX without parameters is a property x. A setX with one parameter makes it writable.
scala
import com.anjunar.scala.universe.introspector.BeanIntrospector
class Person {
private var firstName: String = "Ada"
def getFirstName: String = firstName
def setFirstName(value: String): Unit = firstName = value
}
val model = BeanIntrospector.createWithType(classOf[Person])
val property = model.findProperty("firstName")
val person = new Person
println(property.propertyType.fullName) // java.lang.String
println(property.get(person)) // Ada
property.set(person, "Grace")
println(property.get(person)) // Grace
Properties
What a property offers
Bean and annotated properties share AbstractProperty: one name, the parts it was built from, and its annotations from all of them.
- get(instance): Any
- Calls the getter, or reads the field without one.
- set(instance, value): Unit
- Calls the setter; throws IllegalStateException without one.
- isWriteable: Boolean
- Whether a setter exists.
- propertyType: ResolvedClass
- The getter's or field's type, primitives wrapped.
- field · getter · setter
- The parts, any of them may be null.
- annotations
- Field, getter and setter annotations together.
Scope
Declared or inherited
properties walks every method of the hierarchy; declaredProperties only those of the class itself.
Scala vars are no beans
A Scala var compiles to name() and name_$eq, which BeanIntrospector does not recognize. For Scala classes use annotated properties, or add @BeanProperty.
scala
import scala.beans.BeanProperty
class Person {
@BeanProperty var firstName: String = "Ada" // adds getFirstName and setFirstName
}