Introspection

Exemples

Un exemple d'utilisation de l'introspection est :

Class beanClass = obj.<strong>getClass</strong>();<br> String propertyName = <span class="codeString">"counter"</span>;<br> <strong>BeanInfo </strong>beanInfo = <strong>Introspector.getBeanInfo</strong>(beanClass);<br> <strong>PropertyDescriptor</strong>[] propertyDescriptors = beanInfo.<strong>getPropertyDescriptors</strong>();<br> <br> for (int i = 0; i < propertyDescriptors.length; i++) {<br> <strong>PropertyDescriptor </strong>propertyDescriptor = propertyDescriptors[i];<br> String somePropertyName = propertyDescriptor.<strong>getName</strong>(); <br> if (somePropertyName.equals (propertyName)) { <br> <strong> Method</strong> method = propertyDescriptor.<strong>getReadMethod</strong>(); <span class="codeComment">// Getter</span> <br> Object result = method.<strong>invoke</strong>(obj, new Object[0]); <br> int value = ((Integer)result).intValue() + 1; <span class="codeComment"> // Incrémente<br> </span><strong> </strong>method = propertyDescriptor.<strong>getWriteMethod</strong>(); <span class="codeComment"> // Setter</span> <br> method.<strong>invoke</strong>(obj, new Object[] { new Integer(value) });<br> break;<br> }<br> }

Des exemples d'introspection sont :