views:

114

answers:

3

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?

+6  A: 

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.

NickDK
+2  A: 

java.beans.Introspector.getBeanInfo yields an object implementing java.beans.BeanInfo, which in turn can be used to get PropertyDescriptors and MethodDescriptors (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.

pmf
OK, now I have a PropertyDescriptor. How can I use it to read an attribute from a given object?
tangens
Got it. `value = PropertyDescriptor.getReadMethod.invoke( object )`. A bit complicated, but I'm more flexible this way than with apache beanutils. Thanks.
tangens
A: 

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);
        }
      }
  }
}
mlk
Except that `isFoo` is a valid name for a boolean property named `foo` and `GetFoo` is *not* a valid name for a getter and `getFoo(int index)` is not a Bean getter and, and, and, ... Basically the Bean specification is pretty specific and this code implements only a very small subset of it.
Joachim Sauer