Reputation: 39733
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?
Upvotes: 2
Views: 342
Reputation: 14661
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:
interface Thingie {
Object getAttribute(String attribute);
}
You would have to write an implementation of that that uses reflection.
class Thingie {
Object wrapped;
public Object getAttribute(String attribute) throws Exception {
Method[] methods = wrapped.getClass().getMethods();
for(Method m : methods) {
if (m.getName().equalsIgnoreCase("get"+attribute)) {
return m.invoke(wrapped);
}
}
}
}
Upvotes: 0
Reputation: 7749
java.beans.Introspector.getBeanInfo
yields an object implementing java.beans.BeanInfo
, which in turn can be used to get PropertyDescriptor
s and MethodDescriptor
s (via its getPropertyDescriptors
- and getMethodDescriptors
-methods), which in turn can be used to get the information you actually want.
It is not really less effort than using reflection.
Upvotes: 2
Reputation: 5197
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.
Upvotes: 6