开发者

Need JavaBean utility

开发者 https://www.devze.com 2023-03-08 10:22 出处:网络
Is there a way to get the field na开发者_如何学JAVAme with the given getter method. i get all the getter(s) (getYYY) by using reflection API. now i want to know that \'yyy\' value. so that i can acce

Is there a way to get the field na开发者_如何学JAVAme with the given getter method.

i get all the getter(s) (getYYY) by using reflection API. now i want to know that 'yyy' value. so that i can access that getter method by using expression like #{bean.yyy}.

Example are as given below.

getId -- id

getID -- ID ( i thought it could be 'iD', but it should be 'ID')

getNPI -- NPI

getNPi -- NPi

getNpi -- npi

getNpI -- npI

Please point me to the java bean convention resources if any.


You can download the JavaBeans spec from the Oracle website.

You can introspect beans using the java.beans package:

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

If you decide you really want to, you can also test your property binding expressions using a an EL implementation.


You can use the Java Beans API (package java.beans) instead of using reflection directly to get the bean properties of a class. For example:

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

(Note: Exception handling omitted).

0

精彩评论

暂无评论...
验证码 换一张
取 消