How can I handle a POJO like a bean?

2019-05-21 12:55发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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);
        }
      }
  }
}