Dynamic JavaBeans

Trivial javabeans are one of the most common classes, in software projects. We tend to write the kind of code below, over and over again.

  
class User {
    private String  name = "James";
    private int     age  = 17;

    public User() {}

    public String   getName() {return name;}
    public void     setName(String name) {this.name = name;}

    public int      getAge() {return age;}
    public void     setAge(int age) {this.age = age;}

    public String   toString() {return "User{name="+name+", age="+age+"}";}
    public boolean  equals(Object obj) {
        if (obj == null || !(obj instanceof User)) return false;
        User  user = (User)obj;
        return this.name.equals(user.name) && this.age==user.age;
    }
    public int      hashCode() {return name.hashCode();}
}

By creating a DynamicBean, you can reduce the effort to the definition of an interface and create instances using a bean factory like this.

interface Foo {
   String  getName();
   void    setName();
   int     getNumber();
   boolean isCool();
 }
 Foo  f = (Foo)BeanFactory.getFactory().create(Foo.class, new Object[]{
   "Name"  , "foobar",
   "Number", new Integer(17),
   "Cool"  , Boolean.TRUE
 });

Caveat: The property names starts with a capital letter, a little bit contrary to common practice. This might change somewhat in the near future. You get standard definitions of equals(), hashCode(), toString() and clone() 'for free', as well. The design of this library is based on the following

  • A dynamic bean is a dynamic proxy, generated by java.lang.reflect.Proxy
  • The properties of a bean is maintained by a java.util.HashMap
  • Each bean method is excuted by a BeanAction object
  • Beans are created by a BeanFactory, which contains a repository of BeanDescriptors.
  • A bean descriptor contains a map of actions and default values for all properties.
  • Bean actions are replaceable, which means you can change the implementation of a method.