需要JavaBean实用程序

问题描述

| 有没有一种方法可以使用给定的getter方法获取字段名称。 我通过使用反射API获得了所有的吸气剂(getYYY)。现在我想知道\'yyy \'的值。这样我就可以使用#{bean.yyy}这样的表达式来访问该getter方法。 示例如下。 getId-ID getID-ID(我认为可能是\'iD \',但应该是\'ID \') getNPI-NPI getNPi-NPi getNpi-npi getNpI-npI 如果有的话,请指向Java bean约定资源。     

解决方法

您可以从Oracle网站下载JavaBeans规范。 您可以使用
java.beans
包自检bean:
public class FooBean implements Serializable {
  private String ID;
  public String getID() { return ID; }
  public void setID(String iD) { ID = iD; }

  public static void main(String[] args) throws Exception {
    for (PropertyDescriptor property : Introspector.getBeanInfo(FooBean.class)
        .getPropertyDescriptors()) {
      System.out.println(property.getName()
          + (property.getWriteMethod() == null ? \" (readonly)\" : \"\"));
    }
  }
}
如果您决定要这样做,则还可以使用EL实现来测试属性绑定表达式。     ,您可以使用Java Beans API(软件包
java.beans
)代替直接使用反射来获取类的Bean属性。例如:
import java.beans.*;

// ...
MyBean bean = ...;

BeanInfo beanInfo = Introspector.getBeanInfo(MyBean.class,Object.class);

for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
    System.out.println(\"Property: \" + pd.getName());

    // Get the getter method of a property
    Method getter = pd.getReadMethod();

    // Call it to get the value in an instance of the bean class
    Object value = getter.invoke(bean);

    System.out.println(\"Value: \" + value);
}
(注意:省略了异常处理)。