Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection Beans Property API

Is there any standard way to access Java Bean Property like

class A {    private String name;     public void setName(String name){        this.name = name;    }     public String getName(){        return this.name;    }  } 

So can I access this java bean property name using Reflection API so that when I change the value of property the methods of getName and setName are called automatically when I set and get values of that property

like image 613
Troydm Avatar asked May 02 '11 12:05

Troydm


People also ask

What is the API of JavaBeans?

The JavaBeans API makes it possible to write component software in the Java programming language. Components are self-contained, reusable software units that can be visually composed into composite components, applets, applications, and servlets using visual application builder tools.

What are the properties of beans in Java?

JavaBeans provide default constructor without any conditions or arguments. JavaBeans are serializable and are capable of implementing the Serializable interface. JavaBeans usually have several 'getter' and 'setter' methods. JavaBeans can have several properties that can be read or written.

Does Beanutils use reflection?

As they both ultimately use Reflection you aren't likely to notice much difference, unless the higher-level API is doing things you don't need done. See also java. beans.

What is needed to define a property of a JavaBean?

The JavaBean class must implement either Serializable or Externalizable. The JavaBean class must have a no-arg constructor. All JavaBean properties must have public setter and getter methods. All JavaBean instance variables should be private.


2 Answers

You question is very unclear, but if I get it:

Yes. The java.beans package has the so called Introspector. There you can read the properties of a bean.

BeanInfo info = Introspector.getBeanInfo(Bean.class); PropertyDescriptor[] pds = info.getPropertyDescriptors(); 

You can find the desired PropertyDescriptor by its name and you can call getReadMethod().invoke(..)

like image 138
Bozho Avatar answered Sep 19 '22 19:09

Bozho


What you need is the BeanInfo / Introspector mechanism (see Bozho's answer). However, it's hell to use this directly, so you can use one of the Libraries that offer property-based access. The best-known is probably Apache Commons / BeanUtils (another one is Spring's BeanWrapper abstraction)

Example code:

A someBean = new A();  // access properties as Map Map<String, Object> properties = BeanUtils.describe(someBean); properties.set("name","Fred"); BeanUtils.populate(someBean, properties);  // access individual properties String oldname = BeanUtils.getProperty(someBean,"name"); BeanUtils.setProperty(someBean,"name","Barny");  
like image 37
Sean Patrick Floyd Avatar answered Sep 19 '22 19:09

Sean Patrick Floyd