In most Java projects you have a
lot of classes written only for the
purpose of holding some data.
If you need a bean class which can
hold an int, a String and an
instance of Foo you have to implement the following class:
public class
BadExample {
private int intValue;
private String stringValue;
private Foo foo;
public Foo getFoo() {
return this.foo;
}
public void setFoo(Foo foo) {
this.foo = foo;
}
public int getIntValue() {
return this.intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public String getStringValue() {
return this.stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
}
Of course you could use a
Map/HashMap to hold the data but you would
lose type-safety:
Why not let Java do this boring
job? Use Java
Bean Proxy!
You only have to define the
interface:
public
interface NiceExample {
Foo getFoo();
void setFoo(Foo foo);
int getIntValue();
void setIntValue(int intValue);
String getStringValue();
void setStringValue(String stringValue);
}
The rest is done by Java Bean
Proxy. To get an instance use
ProxyFactory:
NiceExample
niceExample =
ProxyFactory.getProxyInstance(NiceExample.class);
niceExample.setIntValue(44);
System.out.println(niceExample.getIntValue()); //
Would of course result in "44"
ProxyFactory.getProxyInstance will
return a dynamic (runtime) instance
for NiceExample.class which implements hashcode, equals and toString
correctly Additionally this runtime instance is Clone- and
Serializable.
http://sourceforge.net/projects/beanproxy/
Have a lot of fun!