Defining a BeanProperty

Scala provides a convenient shortcut to define bean properties (as we like to call the things that have setX and getX methods and are accessed by reflection), which are used by many Java tools

import scala.reflect.BeanProperty
 
class Pilot(@BeanProperty var name: String, @BeanProperty var points: Int) {
 
 def addPoints(apoints: Int): Int = {
    points += apoints
    points
 }
 
 override def toString(): String = name + "/" + points
}

Looking into the generated classfile, we can convince ourselves that the get and set methods are actually there.

/tmp$ scalac -d /tmp /tmp/pilot.scala 
/tmp$ javap -classpath /tmp Pilot
Compiled from "pilot.scala"
public class Pilot extends java.lang.Object implements scala.ScalaObject{
    public Pilot(java.lang.String, int);
    public void setPoints(int);
    public int getPoints();
    public void setName(java.lang.String);
    public java.lang.String getName();
    public java.lang.String toString();
    public int addPoints(int);
    public void points_$eq(int);
    public int points();
    public void name_$eq(java.lang.String);
    public java.lang.String name();
    public int $tag();
}

After 2.6.2, you should be able to annotate a class with the BeanInfo annotation, like so:

@BeanInfo
class MyBean {
  var name = "Ross"
  val age = 40
  
  def create {
  }
}

An additional .class file will be generated by the compiler, where the name of the class ends with “BeanInfo”. The standard Introspector will look for these BeanInfo classes automatically. Each public var will become a read-write property. Each val will become a read-only property. Methods not related to the vars will become operations.

This makes a very compact notation for creating a data-oriented JavaBean.

 
code/defining-bean-properties.txt · Last modified: 2008/01/23 21:04 by 207.152.147.19
 
Recent changes RSS feed Valid XHTML 1.0 Driven by DokuWiki