Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get bean property getter or setter by reflection?

Suppose I have a handle on an object of type , and I'm told by configuration that it has a bean property of type int with the name age. How can I retrieve the getter for this document?

Is there a better way than prepending "get" and capitalizing the "a" in age, and looking for a method of that name via reflection?

like image 801
C. Ross Avatar asked Jul 27 '11 13:07

C. Ross


People also ask

What tag is used to invoke the setter method of beans?

Using * to call all setter methods of java bean The property attribute of <jsp:setProperty> contains '*' as its value. This tag calls only those setter methods of the property whose names are available in the requested form field.

Is accessor getter or setter?

Given this, getters and setters are also known as accessors and mutators, respectively. The getter method returns the value of the attribute. The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values.


1 Answers

Take a look at java.beans.Introspector. This class allows you to get the list of properties on a class.

If you know property name you can call

Method getter = new PropertyDescriptor(propertyName, beanClass).getReadMethod();

See Also:

  • java.beans.PropertyDescriptor
  • java.lang.reflect.Method
like image 159
Sergey Aslanov Avatar answered Sep 23 '22 23:09

Sergey Aslanov