How can I access a simple java object as a bean?
For example:
class Simple {
private String foo;
String getFoo() {
return foo;
}
private void setFoo( String foo ) {
this.foo = foo;
}
}
Now I want to use this object like this:
Simple simple = new Simple();
simple.setFoo( "hello" );
checkSettings( simple );
So I'm looking for the implementation of the method checkSettings( Object obj )
:
public boolean checkSettings( Object obj ) {
// pseudocode here
Bean bean = new Bean( obj );
if( "hello".equals( bean.getAttribute( "foo" ) ) {
return true;
}
return false;
}
The java language contains a package called java.beans
which sounds like it could help me. But I don't find a good starting point.
Any hints?
As stated in the question comments above I'm still not sure what you want, but it sort of sounds like you want to wrap an object gets & sets to an interface with a getAttribute. This is not what I think of as a "bean".
So you have an interface:
You would have to write an implementation of that that uses reflection.
java.beans.Introspector.getBeanInfo
yields an object implementingjava.beans.BeanInfo
, which in turn can be used to getPropertyDescriptor
s andMethodDescriptor
s (via itsgetPropertyDescriptors
- andgetMethodDescriptors
-methods), which in turn can be used to get the information you actually want.It is not really less effort than using reflection.
I think the functionality you're looking for resembles the one from the BeanUtils class of apache-commons:
http://commons.apache.org/beanutils/
Take a look at the getProperty() method of BeanUtils.