List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:org.grails.beans.support.CachedIntrospectionResults.java
/** * Compare the given {@code PropertyDescriptors} and return {@code true} if * they are equivalent, i.e. their read method, write method, property type, * property editor and flags are equivalent. * @see java.beans.PropertyDescriptor#equals(Object) *//*w w w . j a va 2s. c o m*/ public static boolean equals(PropertyDescriptor pd, PropertyDescriptor otherPd) { return (ObjectUtils.nullSafeEquals(pd.getReadMethod(), otherPd.getReadMethod()) && ObjectUtils.nullSafeEquals(pd.getWriteMethod(), otherPd.getWriteMethod()) && ObjectUtils.nullSafeEquals(pd.getPropertyType(), otherPd.getPropertyType()) && ObjectUtils.nullSafeEquals(pd.getPropertyEditorClass(), otherPd.getPropertyEditorClass()) && pd.isBound() == otherPd.isBound() && pd.isConstrained() == otherPd.isConstrained()); }
From source file:org.jaffa.util.BeanHelper.java
/** Clones the input bean, performing a deep copy of its properties. * @param bean the bean to be cloned./*from w ww . j a va 2 s .c o m*/ * @param deepCloneForeignField if false, then the foreign-fields of a GraphDataObject will not be deep cloned. * @return a clone of the input bean. * @throws IllegalAccessException if the underlying method is inaccessible. * @throws InvocationTargetException if the underlying method throws an exception. * @throws InstantiationException if the bean cannot be instantiated. * @throws IntrospectionException if an exception occurs during introspection. */ public static Object cloneBean(Object bean, boolean deepCloneForeignField) throws IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException { if (bean == null) return bean; Class beanClass = bean.getClass(); // Return the input as-is, if immutable if (beanClass == String.class || beanClass == Boolean.class || Number.class.isAssignableFrom(beanClass) || IDateBase.class.isAssignableFrom(beanClass) || Currency.class.isAssignableFrom(beanClass) || beanClass.isPrimitive()) { return bean; } // Handle an array if (beanClass.isArray()) { Class componentType = beanClass.getComponentType(); int length = Array.getLength(bean); Object clone = Array.newInstance(componentType, length); for (int i = 0; i < length; i++) { Object arrayElementClone = cloneBean(Array.get(bean, i), deepCloneForeignField); Array.set(clone, i, arrayElementClone); } return clone; } // Handle a Collection if (bean instanceof Collection) { Collection clone = (Collection) bean.getClass().newInstance(); for (Object collectionElement : (Collection) bean) { Object collectionElementClone = cloneBean(collectionElement, deepCloneForeignField); clone.add(collectionElementClone); } return clone; } // Handle a Map if (bean instanceof Map) { Map clone = (Map) bean.getClass().newInstance(); for (Iterator i = ((Map) bean).entrySet().iterator(); i.hasNext();) { Map.Entry me = (Map.Entry) i.next(); Object keyClone = cloneBean(me.getKey(), deepCloneForeignField); Object valueClone = cloneBean(me.getValue(), deepCloneForeignField); clone.put(keyClone, valueClone); } return clone; } // Invoke the 'public Object clone()' method, if available if (bean instanceof Cloneable) { try { Method cloneMethod = beanClass.getMethod("clone"); return cloneMethod.invoke(bean); } catch (NoSuchMethodException e) { // do nothing } } // Create a clone using bean introspection Object clone = beanClass.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); if (beanInfo != null) { PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); if (pds != null) { // Obtain a GraphMapping; only if foreign-fields are not to be cloned //Use reflection to achieve the following: //GraphMapping graphMapping = !deepCloneForeignField && bean instanceof GraphDataObject ? MappingFactory.getInstance(bean) : null; Object graphMapping = null; Method isForeignFieldMethod = null; try { if (!deepCloneForeignField && Class.forName("org.jaffa.soa.graph.GraphDataObject").isInstance(bean)) { graphMapping = Class.forName("org.jaffa.soa.dataaccess.MappingFactory") .getMethod("getInstance", Object.class).invoke(null, bean); isForeignFieldMethod = graphMapping.getClass().getMethod("isForeignField", String.class); } } catch (Exception e) { // do nothing since JaffaSOA may not be deployed if (log.isDebugEnabled()) log.debug("Exception in obtaining the GraphMapping", e); } for (PropertyDescriptor pd : pds) { if (pd.getReadMethod() != null && pd.getWriteMethod() != null) { // Do not clone a foreign-field Object property = pd.getReadMethod().invoke(bean); //Use reflection to achieve the following: //Object propertyClone = graphMapping != null && graphMapping.isForeignField(pd.getName()) ? property : cloneBean(property, deepCloneForeignField); Object propertyClone = null; boolean propertyCloned = false; if (graphMapping != null && isForeignFieldMethod != null) { try { if ((Boolean) isForeignFieldMethod.invoke(graphMapping, pd.getName())) { propertyClone = property; propertyCloned = true; } } catch (Exception e) { // do nothing since JaffaSOA may not be deployed if (log.isDebugEnabled()) log.debug("Exception in invoking GraphMapping.isForeignField()", e); } } if (!propertyCloned) propertyClone = cloneBean(property, deepCloneForeignField); pd.getWriteMethod().invoke(clone, propertyClone); } } } } return clone; }
From source file:de.alpharogroup.lang.object.MergeObjectExtensions.java
/** * Merge the given property to the given 'to' object with the given 'with' object. * * @param <TO>//w ww . j a v a 2s . c om * the generic type of the object to merge in * @param <WITH> * the generic type of the object to merge with * @param toObject * the object to merge in * @param withObject * the object to merge with * @param propertyDescriptor * the property descriptor * @throws InvocationTargetException * if the property accessor method throws an exception * @throws IllegalAccessException * if the caller does not have access to the property accessor method */ public static final <TO, WITH> void mergeProperty(final TO toObject, final WITH withObject, final PropertyDescriptor propertyDescriptor) throws IllegalAccessException, InvocationTargetException { if (PropertyUtils.isReadable(toObject, propertyDescriptor.getName()) && PropertyUtils.isWriteable(toObject, propertyDescriptor.getName())) { final Method getter = propertyDescriptor.getReadMethod(); final Object value = getter.invoke(withObject); if (!value.isDefaultValue()) { final Method setter = propertyDescriptor.getWriteMethod(); setter.invoke(toObject, value); } } }
From source file:org.bibsonomy.layout.util.JabRefModelConverter.java
/** * Convert a JabRef BibtexEntry into a BibSonomy post * //from w w w .j a v a 2 s . c o m * @param entry * @return */ public static Post<? extends Resource> convertEntry(final BibtexEntry entry) { try { final Post<BibTex> post = new Post<BibTex>(); final BibTex bibtex = new BibTex(); post.setResource(bibtex); final List<String> knownFields = new ArrayList<String>(); final BeanInfo info = Introspector.getBeanInfo(bibtex.getClass()); final PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); bibtex.setMisc(""); // set all known properties of the BibTex for (final PropertyDescriptor pd : descriptors) if (present(entry.getField((pd.getName().toLowerCase()))) && !JabRefModelConverter.EXCLUDE_FIELDS.contains(pd.getName().toLowerCase())) { pd.getWriteMethod().invoke(bibtex, entry.getField(pd.getName().toLowerCase())); knownFields.add(pd.getName()); } // Add not known Properties to misc for (final String field : entry.getAllFields()) if (!knownFields.contains(field) && !JabRefModelConverter.EXCLUDE_FIELDS.contains(field)) bibtex.addMiscField(field, entry.getField(field)); bibtex.serializeMiscFields(); // set the key bibtex.setBibtexKey(entry.getCiteKey()); bibtex.setEntrytype(entry.getType().getName().toLowerCase()); // set the date of the post final String timestamp = entry.getField("timestamp"); if (present(timestamp)) post.setDate(sdf.parse(timestamp)); final String abstractt = entry.getField("abstract"); if (present(abstractt)) bibtex.setAbstract(abstractt); final String keywords = entry.getField("keywords"); if (present(keywords)) post.setTags(TagUtils.parse(keywords.replaceAll(jabRefKeywordSeparator, " "))); // Set the groups if (present(entry.getField("groups"))) { final String[] groupsArray = entry.getField("groups").split(" "); final Set<Group> groups = new HashSet<Group>(); for (final String group : groupsArray) groups.add(new Group(group)); post.setGroups(groups); } final String description = entry.getField("description"); if (present(description)) post.setDescription(description); final String comment = entry.getField("comment"); if (present(comment)) post.setDescription(comment); final String month = entry.getField("month"); if (present(month)) bibtex.setMonth(month); return post; } catch (final Exception e) { System.out.println(e.getStackTrace()); log.debug("Could not convert JabRef entry into BibSonomy post.", e); } return null; }
From source file:com.github.dozermapper.core.util.ReflectionUtils.java
public static Class<?> determineGenericsType(Class<?> parentClazz, PropertyDescriptor propDescriptor) { Class<?> result = null; //Try getter and setter to determine the Generics type in case one does not exist if (propDescriptor.getWriteMethod() != null) { result = determineGenericsType(parentClazz, propDescriptor.getWriteMethod(), false); }// www. j a va2s .c o m if (result == null && propDescriptor.getReadMethod() != null) { result = determineGenericsType(parentClazz, propDescriptor.getReadMethod(), true); } return result; }
From source file:es.caib.zkib.jxpath.util.ValueUtils.java
/** * Modifies the value of the bean's property represented by * the supplied property descriptor./*from w w w. jav a 2s .c o m*/ * @param bean to read * @param propertyDescriptor indicating what to read * @param value to set */ public static void setValue(Object bean, PropertyDescriptor propertyDescriptor, Object value) { try { Method method = getAccessibleMethod(propertyDescriptor.getWriteMethod()); if (method == null) { throw new JXPathException("No write method"); } value = convert(value, propertyDescriptor.getPropertyType()); method.invoke(bean, new Object[] { value }); } catch (Exception ex) { throw new JXPathException("Cannot modify property: " + (bean == null ? "null" : bean.getClass().getName()) + "." + propertyDescriptor.getName(), ex); } }
From source file:org.jaffa.util.BeanHelper.java
/** This method will introspect the bean & get the setter method for the input propertyName. * It will then try & convert the propertyValue to the appropriate datatype. * Finally it will invoke the setter.// www. j a v a 2 s . c o m * @return A true indicates, the property was succesfully set to the passed value. A false indicates the property doesn't exist or the propertyValue passed is not compatible with the setter. * @param bean The bean class to be introspected. * @param propertyName The Property being searched for. * @param propertyValue The value to be set. * @throws IntrospectionException if an exception occurs during introspection. * @throws IllegalAccessException if the underlying method is inaccessible. * @throws InvocationTargetException if the underlying method throws an exception. */ public static boolean setField(Object bean, String propertyName, Object propertyValue) throws IntrospectionException, IllegalAccessException, InvocationTargetException { boolean result = false; if (bean instanceof DynaBean) { try { PropertyUtils.setProperty(bean, propertyName, propertyValue); result = true; } catch (NoSuchMethodException ignore) { // If the bean is a FlexBean instance, then the field could exist on the associated persistentObject if (bean instanceof FlexBean && ((FlexBean) bean).getPersistentObject() != null) { try { PropertyUtils.setProperty(((FlexBean) bean).getPersistentObject(), propertyName, propertyValue); result = true; } catch (NoSuchMethodException ignore2) { } } } } else { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); if (beanInfo != null) { PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); if (pds != null) { for (PropertyDescriptor pd : pds) { if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName)) { Method m = pd.getWriteMethod(); Object convertedPropertyValue = null; if (propertyValue != null) { if (pd.getPropertyType().isEnum()) { convertedPropertyValue = findEnum(pd.getPropertyType(), propertyValue.toString()); } else { try { convertedPropertyValue = DataTypeMapper.instance().map(propertyValue, pd.getPropertyType()); } catch (Exception e) { // do nothing break; } } } m.invoke(bean, new Object[] { convertedPropertyValue }); result = true; break; } } } } try { // Finally, check the FlexBean if (!result && bean instanceof IFlexFields && ((IFlexFields) bean).getFlexBean() != null && ((IFlexFields) bean).getFlexBean().getDynaClass() .getDynaProperty(propertyName) != null) { ((IFlexFields) bean).getFlexBean().set(propertyName, propertyValue); result = true; } } catch (Exception ignore) { } } return result; }
From source file:de.escalon.hypermedia.spring.uber.UberUtils.java
/** * Renders input fields for bean properties of bean to add or update or patch. * * @param uberFields//from ww w. j a v a2 s . co m * to add to * @param beanType * to render * @param annotatedParameters * which describes the method * @param annotatedParameter * which requires the bean * @param currentCallValue * sample call value */ private static void recurseBeanCreationParams(List<UberField> uberFields, Class<?> beanType, ActionDescriptor annotatedParameters, ActionInputParameter annotatedParameter, Object currentCallValue, String parentParamName, Set<String> knownFields) { // TODO collection, map and object node creation are only describable by an annotation, not via type reflection if (ObjectNode.class.isAssignableFrom(beanType) || Map.class.isAssignableFrom(beanType) || Collection.class.isAssignableFrom(beanType) || beanType.isArray()) { return; // use @Input(include) to list parameter names, at least? Or mix with hdiv's form builder? } try { Constructor[] constructors = beanType.getConstructors(); // find default ctor Constructor constructor = PropertyUtils.findDefaultCtor(constructors); // find ctor with JsonCreator ann if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } Assert.notNull(constructor, "no default constructor or JsonCreator found for type " + beanType.getName()); int parameterCount = constructor.getParameterTypes().length; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; // TODO use required attribute of JsonProperty for required fields String paramName = jsonProperty.value(); Class parameterType = parameters[paramIndex]; Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName); MethodParameter methodParameter = new MethodParameter(constructor, paramIndex); addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter, annotatedParameters, parentParamName, paramName, parameterType, propertyValue, knownFields); paramIndex++; // increase for each @JsonProperty } } } Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator " + constructor.getName() + " are annotated with @JsonProperty"); } Set<String> knownConstructorFields = new HashSet<String>(uberFields.size()); for (UberField sirenField : uberFields) { knownConstructorFields.add(sirenField.getName()); } // TODO support Option provider by other method args? Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType); // add input field for every setter for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) { final Method writeMethod = propertyDescriptor.getWriteMethod(); String propertyName = propertyDescriptor.getName(); if (writeMethod == null || knownFields.contains(parentParamName + propertyName)) { continue; } final Class<?> propertyType = propertyDescriptor.getPropertyType(); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, propertyName); MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0); addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter, annotatedParameters, parentParamName, propertyName, propertyType, propertyValue, knownConstructorFields); } } catch (Exception e) { throw new RuntimeException("Failed to write input fields for constructor", e); } }
From source file:it.sample.parser.util.CommonsUtil.java
/** * Metodo di utilita' per rendere null un'istanza di una classe che e' istanziata ma che ha tutti i campi null * /* w ww . j a va 2s. co m*/ * @param instance */ public static <T> void sanitizeObject(T instance) { PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(instance); if (descriptors != null) { for (PropertyDescriptor descriptor : descriptors) { try { String propertyName = descriptor.getName(); if (descriptor.getReadMethod() != null) { Object val = PropertyUtils.getProperty(instance, propertyName); if (val != null && !BeanUtils.isSimpleProperty(val.getClass()) && descriptor.getWriteMethod() != null && !isFilled(val) && !val.getClass().getName().startsWith("java.util")) { PropertyUtils.setProperty(instance, propertyName, null); } } } catch (Exception e) { e.printStackTrace(); } } } }
From source file:disko.DU.java
@SuppressWarnings("unchecked") public static <T> T cloneObject(T p, Mapping<Pair<Object, String>, Boolean> propertyFilter) throws Exception { if (p == null) return null; if (p instanceof Cloneable) { Method cloneMethod = p.getClass().getMethod("clone", (Class[]) null); if (cloneMethod != null) return (T) cloneMethod.invoke(p, (Object[]) null); } else if (p.getClass().isArray()) { Object[] A = (Object[]) p; Class<?> type = p.getClass(); Object[] ac = (Object[]) Array.newInstance(type.getComponentType(), A.length); for (int i = 0; i < A.length; i++) ac[i] = cloneObject(A[i], propertyFilter); return (T) ac; } else if (identityCloneClasses.contains(p.getClass())) return p; ///* www. j a v a 2 s .c o m*/ // Need to implement cloning ourselves. We do this by copying bean properties. // Constructor<?> cons = null; try { cons = p.getClass().getConstructor((Class[]) null); } catch (Throwable t) { return p; } Object copy = cons.newInstance((Object[]) null); if (p instanceof Collection) { Collection<Object> cc = (Collection<Object>) copy; for (Object el : (Collection<?>) p) cc.add(cloneObject(el, propertyFilter)); } else if (p instanceof Map) { Map<Object, Object> cm = (Map<Object, Object>) copy; for (Object key : ((Map<Object, Object>) p).keySet()) cm.put(key, cloneObject(((Map<Object, Object>) p).get(key), propertyFilter)); } else { BeanInfo bean_info = Introspector.getBeanInfo(p.getClass()); PropertyDescriptor beanprops[] = bean_info.getPropertyDescriptors(); if (beanprops == null || beanprops.length == 0) copy = p; else for (PropertyDescriptor desc : beanprops) { Method rm = desc.getReadMethod(); Method wm = desc.getWriteMethod(); if (rm == null || wm == null) continue; Object value = rm.invoke(p, (Object[]) null); if (propertyFilter == null || propertyFilter.eval(new Pair<Object, String>(p, desc.getName()))) value = cloneObject(value, propertyFilter); wm.invoke(copy, new Object[] { value }); } } return (T) copy; }