How can I handle POJO as a bean?

How can I access a simple java object as a bean?

For instance:

class Simple {
    private String foo;
    String getFoo() {
        return foo;
    }
    private void setFoo( String foo ) {
        this.foo = foo;
    }
}

Now I want to use this object as follows:

Simple simple = new Simple();
simple.setFoo( "hello" );

checkSettings( simple );

So, I am looking for an implementation of a 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.beansthat sounds like it can help me. But I did not find a good starting point.

Any clues?

+2
source share
3 answers

java.beans.Introspector.getBeanInfo , java.beans.BeanInfo, , , PropertyDescriptor MethodDescriptor ( getPropertyDescriptors - getMethodDescriptors), , , .

, .

+2

, , , , BeanUtils apache-commons:

http://commons.apache.org/beanutils/

getProperty() BeanUtils.

+6

, , , , , , , getAttribute. , "bean".

, :

interface Thingie {
     Object getAttribute(String attribute);
}

You need to write an implementation of what reflection uses.

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

Source: https://habr.com/ru/post/1731273/


All Articles