List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptor
public static PropertyDescriptor getPropertyDescriptor(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Retrieve the property descriptor for the specified property of the specified bean, or return null
if there is no such descriptor.
For more details see PropertyUtilsBean
.
From source file:com.tonbeller.wcf.expr.ExprUtils.java
public static PropertyDescriptor getPropertyDescriptor(ExprContext context, String expr) { if (!ExprUtils.isExpression(expr) || !expr.endsWith("}") || expr.indexOf('.') < 0) throw new IllegalArgumentException("'#{bean.property}' expected"); int pos = expr.indexOf('.'); String name = expr.substring(2, pos); Object bean = context.findBean(name); if (bean == null) throw new IllegalArgumentException("bean \"" + name + "\" not found"); String path = expr.substring(pos + 1, expr.length() - 1); try {//from www. ja v a 2s . c om return PropertyUtils.getPropertyDescriptor(bean, path); } catch (Exception e) { logger.error(null, e); return null; } }
From source file:com.hengyi.japp.sap.convert.impl.FieldCopyBase.java
protected void initBeanPropertyWriteMethod(Object bean, JCoRecord record) throws Exception { PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, beanPropertyName); beanPropertyWriteMethod = descriptor.getWriteMethod(); if (beanPropertyWriteMethod == null) { return;/*from ww w .j a v a2 s. c o m*/ } String methodName = beanPropertyWriteMethod.getName(); String expectedTypeString = record.getMetaData().getClassNameOfField(sapFieldName); Class<?> sapFieldType = Class.forName(expectedTypeString); beanPropertyWriteMethod = MethodUtils.getMatchingAccessibleMethod(bean.getClass(), methodName, sapFieldType); }
From source file:com.cloudera.csd.validation.references.components.ReflectionHelper.java
/** * The value of the property is returned for the target object. * * @param targetObject the target object. * @param propertyName the property name. * @param clazz the class of the value./* ww w . j av a 2 s.c o m*/ * @param <T> the type of the value. * @return the value of the property */ @Nullable public static <T> T propertyValueByName(Object targetObject, String propertyName, Class<T> clazz) { try { PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(targetObject, propertyName); Object result = invokeMethod(desc.getReadMethod(), targetObject); return (T) result; } catch (IllegalAccessException e) { throw new IllegalStateException("Could not invoke " + propertyName, e); } catch (InvocationTargetException e) { throw new IllegalStateException("Could not invoke " + propertyName, e); } catch (NoSuchMethodException e) { throw new IllegalStateException("Could not invoke " + propertyName, e); } }
From source file:gr.interamerican.bo2.utils.TestJavaBeanUtils.java
/** * Unit test for getProperty.//from w w w . j ava 2 s . c om * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ @Test public void testGetProperty_noGetter() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { BeanWithNoFieldGetter bean = new BeanWithNoFieldGetter(); String value = "hello"; //$NON-NLS-1$ bean.setField1(value); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, "field1"); //$NON-NLS-1$ String actual = (String) JavaBeanUtils.getProperty(pd, bean); assertEquals(value, actual); }
From source file:jp.terasoluna.fw.util.GenericPropertyUtil.java
/** * <code>JavaBean</code>??? ?? * @param bean <code>JavaBean</code> * @param name <code>Generics</code>???? * @return <code>JavaBean</code>????? * @throws IllegalArgumentException <code>JavaBean</code>?? ?????????? *///w ww.j a va 2 s .com protected static Method getMethod(Object bean, String name) throws IllegalArgumentException { PropertyDescriptor descriptor = null; try { descriptor = PropertyUtils.getPropertyDescriptor(bean, name); } catch (IllegalAccessException e) { throw new IllegalArgumentException( "Failed to detect getter for " + bean.getClass().getName() + "#" + name, e); } catch (InvocationTargetException e) { throw new IllegalArgumentException( "Failed to detect getter for " + bean.getClass().getName() + "#" + name, e); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "Failed to detect getter for " + bean.getClass().getName() + "#" + name, e); } Method method = null; if (descriptor != null) { method = descriptor.getReadMethod(); } if (method == null) { throw new IllegalArgumentException(bean.getClass().getName() + " has no getter for property " + name); } return method; }
From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java
/** * Converts JSON types to "normal" java types. * * @param obj the object to convert (must not be * <code>null</code>, but can be * <code>JSONObject.NULL</code>). * @param targetType the desired target type (must not be * <code>null</code>). * * @return the converted object.// w ww . j a v a2 s. c om * * @exception IllegalArgumentException thrown if the desired * conversion is not possible. */ public Object toJava(Object obj, Class targetType) { try { if (obj == JSONObject.NULL) { if (targetType == Integer.TYPE || targetType == Double.TYPE || targetType == Boolean.TYPE || targetType == Long.TYPE || targetType == Float.TYPE) { // null does not work for primitive types throw new Exception(); } return null; } if (obj instanceof JSONArray) { Class componentType; if (targetType == null || targetType == Object.class) { componentType = null; } else { componentType = targetType.getComponentType(); } JSONArray jsonArray = (JSONArray) obj; int length = jsonArray.length(); Object retVal = Array.newInstance((componentType == null ? Object.class : componentType), length); for (int i = 0; i < length; ++i) { Array.set(retVal, i, toJava(jsonArray.get(i), componentType)); } return retVal; } if (obj instanceof JSONObject) { JSONObject jsonObject = (JSONObject) obj; JSONArray names = jsonObject.names(); if (targetType == Map.class || targetType == HashMap.class || targetType == null || targetType == Object.class) { HashMap retVal = new HashMap(); if (names != null) { int length = names.length(); String name; for (int i = 0; i < length; ++i) { name = names.getString(i); retVal.put(name, toJava(jsonObject.get(name), null)); } } return retVal; } Object bean; String requestedTypeName = jsonObject.optString("class", null); if (requestedTypeName != null) { Class clazz = resolveClassHint(requestedTypeName, targetType); if (clazz == null || !targetType.isAssignableFrom(clazz)) { throw new Exception(); } bean = clazz.newInstance(); // TODO: support constructor parameters } else { bean = targetType.newInstance(); } if (names != null) { int length = names.length(); String name; PropertyDescriptor desc; for (int i = 0; i < length; ++i) { name = names.getString(i); if (!"class".equals(name)) { desc = PropertyUtils.getPropertyDescriptor(bean, name); if (desc != null && desc.getWriteMethod() != null) { PropertyUtils.setSimpleProperty(bean, name, toJava(jsonObject.get(name), desc.getPropertyType())); } } } } return bean; } if (targetType == null || targetType == Object.class) { return obj; } Class actualTargetType; Class sourceType = obj.getClass(); if (targetType == Integer.TYPE) { actualTargetType = Integer.class; } else if (targetType == Boolean.TYPE) { actualTargetType = Boolean.class; } else if ((targetType == Double.TYPE || targetType == Double.class) && Number.class.isAssignableFrom(sourceType)) { return new Double(((Number) obj).doubleValue()); // TODO: maybe return obj directly if it's a Double } else if ((targetType == Float.TYPE || targetType == Float.class) && Number.class.isAssignableFrom(sourceType)) { return new Float(((Number) obj).floatValue()); } else if ((targetType == Long.TYPE || targetType == Long.class) && Number.class.isAssignableFrom(sourceType)) { return new Long(((Number) obj).longValue()); } else { actualTargetType = targetType; } if (!actualTargetType.isAssignableFrom(sourceType)) { throw new Exception(); } return obj; } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Cannot convert " + (obj == null ? null : obj.getClass().getName()) + " to " + (targetType == null ? null : targetType.getName())); } }
From source file:br.bookmark.db.util.ResultSetUtils.java
/** * Populate the JavaBean properties of the specified bean, based on * the specified name/value pairs. This method uses Java reflection APIs * to identify corresponding "property setter" method names. The type of * the value in the Map must match the setter type. The setter must * expect a single arguement (the one on the Map). * <p>/*from ww w.j a v a 2s . c om*/ * The particular setter method to be called for each property is * determined using the usual JavaBeans introspection mechanisms. Thus, * you may identify custom setter methods using a BeanInfo class that is * associated with the class of the bean itself. If no such BeanInfo * class is available, the standard method name conversion ("set" plus * the capitalized name of the property in question) is used. * <p> * <strong>NOTE</strong>: It is contrary to the JavaBeans Specification * to have more than one setter method (with different argument * signatures) for the same property. * <p> * This method adopted from the Jakarta Commons BeanUtils.populate. * * @author Craig R. McClanahan * @author Ralph Schaer * @author Chris Audley * @author Rey Franois * @author Gregor Raman * @author Ted Husted * * @param bean JavaBean whose properties are being populated * @param properties Map keyed by property name, with the * corresponding value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @deprecated Use BeanUtils.CopyProperties instead. */ public static void setProperties(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException { if ((bean == null) || (properties == null)) return; /* if (debug >= 1) System.out.println("BeanUtils.populate(" + bean + ", " + properties + ")"); */ // Loop through the property name/value pairs to be set Iterator names = properties.keySet().iterator(); while (names.hasNext()) { // Identify the property name and value(s) to be assigned String name = (String) names.next(); if (name == null) continue; // Get the property descriptor of the requested property (if any) PropertyDescriptor descriptor = null; try { descriptor = PropertyUtils.getPropertyDescriptor(bean, name); } catch (Throwable t) { /* if (debug >= 1) System.out.println(" getPropertyDescriptor: " + t); */ descriptor = null; } if (descriptor == null) { /* if (debug >= 1) System.out.println(" No such property, skipping"); */ continue; } /* if (debug >= 1) System.out.println(" Property descriptor is '" + descriptor + "'"); */ // Identify the relevant setter method (if there is one) Method setter = descriptor.getWriteMethod(); if (setter == null) { /* if (debug >= 1) System.out.println(" No setter method, skipping"); */ continue; } // Obtain value to be set Object[] args = new Object[1]; args[0] = properties.get(name); // This MUST match setter type /* if (debug >= 1) System.out.println(" name='" + name + "', value.class='" + (value == null ? "NONE" : value.getClass().getName()) + "'"); */ /* if (debug >= 1) System.out.println(" Setting to " + (parameters[0] == null ? "NULL" : "'" + parameters[0] + "'")); */ // Invoke the setter method setter.invoke(bean, args); } /* if (debug >= 1) System.out.println("============================================"); */ }
From source file:gr.interamerican.bo2.utils.TestJavaBeanUtils.java
/** * Unit test for setProperty.//from w w w. j a v a2s. co m * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ @Test public void testSetProperty() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { BeanWith2Fields bean = new BeanWith2Fields(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, "field1"); //$NON-NLS-1$ String value = "string"; //$NON-NLS-1$ JavaBeanUtils.setProperty(pd, value, bean); assertEquals(value, bean.getField1()); }
From source file:name.martingeisse.common.javascript.serialize.BeanToJavascriptObjectSerializer.java
/** * Serializes the specified bean fields. * @param bean the bean to get values from * @param assembler the Javascript assembler to use * @param fieldNames the names of the fields to serialize *///w ww .j a v a2 s. co m public void serializeFields(final Object bean, final JavascriptAssembler assembler, final String... fieldNames) { try { for (final String serializedName : fieldNames) { String beanPropertyName = mapSerializedNameToPropertyName(serializedName); final PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(bean, beanPropertyName); if (propertyDescriptor == null) { throw new RuntimeException("no such property: " + serializedName + " (bean property name: " + beanPropertyName + ")"); } final Method readMethod = propertyDescriptor.getReadMethod(); final Object value = readMethod.invoke(bean); assembler.prepareObjectProperty(serializedName); serializeFieldValue(bean, assembler, beanPropertyName, serializedName, value); } } catch (final Exception e) { throw new RuntimeException(e); } }
From source file:com.cloudera.csd.validation.references.components.ReflectionHelper.java
/** * Returns the property getter method if one exists, 'null' otherwise. * @param obj The object which has the property 'propertyName' * @param propertyName The property name, e.g., "name". * @return/* w w w.j av a 2s .c o m*/ */ @Nullable public static Method propertyGetter(Object obj, String propertyName) { Preconditions.checkNotNull(obj); Preconditions.checkNotNull(propertyName); try { PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(obj, propertyName); return desc.getReadMethod(); } catch (IllegalAccessException e) { throw new IllegalStateException( "Could not access " + propertyName + " of " + obj.getClass().getSimpleName(), e); } catch (InvocationTargetException e) { throw new IllegalStateException( "Could not access " + propertyName + " of " + obj.getClass().getSimpleName(), e); } catch (NoSuchMethodException e) { throw new IllegalStateException( "No such property " + propertyName + " for " + obj.getClass().getSimpleName(), e); } }