List of usage examples for java.beans PropertyDescriptor getName
public String getName()
From source file:com.stephenduncanjr.easymock.EasyMockPropertyUtils.java
/** * Gets the properties and values from the object as a map, ignoring the * properties specified.//from w w w . jav a 2 s. co m * * @param bean * @param ignoredProperties * @return map of properties names to values. */ private static Map<String, Object> retrieveAndFilterProperties(final Object bean, final List<String> ignoredProperties) { final Map<String, Object> map = new HashMap<String, Object>(); try { for (final PropertyDescriptor p : PropertyUtils.getPropertyDescriptors(bean)) { if (!ignoredProperties.contains(p.getName()) && !"class".equals(p.getName())) { final Method readMethod = p.getReadMethod(); if (readMethod != null) { map.put(p.getName(), readMethod.invoke(bean)); } } } } catch (final IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (final InvocationTargetException e) { throw new IllegalArgumentException(e); } return map; }
From source file:com.ksmpartners.ernie.util.TestUtil.java
/** * Performs the getter/setter tests on the java object. The method works by * iterating over the declared fields (ignoring static fields) and ensures * that each field has a getter and setter (as indicated by the parameters) * and that the results of calling the setter followed by the getter match. * <p>//from w w w.java 2s. co m */ public static void populateFields(Class clazz, Object target) { PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(target); for (PropertyDescriptor property : properties) { final String qName = "[" + clazz.getName() + "]." + property.getName(); final Class<?> fieldType = property.getPropertyType(); // ignore getClass() and isEmpty() if (property.getName().equals("class") || property.getName().equals("empty")) continue; // create a test value for our setter Object setValue = createSetValue(qName, fieldType); testProperty(target, property, setValue, qName); } }
From source file:io.fabric8.core.jmx.BeanUtils.java
public static List<String> getFields(Class clazz) { List<String> answer = new ArrayList<String>(); try {//w w w . java 2 s . co m for (PropertyDescriptor desc : PropertyUtils.getPropertyDescriptors(clazz)) { if (desc.getReadMethod() != null) { answer.add(desc.getName()); } } } catch (Exception e) { throw new FabricException("Failed to get property descriptors for " + clazz.toString(), e); } // few tweaks to maintain compatibility with existing views for now... if (clazz.getSimpleName().equals("Container")) { answer.add("parentId"); answer.add("versionId"); answer.add("profileIds"); answer.add("childrenIds"); answer.remove("fabricService"); } else if (clazz.getSimpleName().equals("Profile")) { answer.add("id"); answer.add("parentIds"); answer.add("childIds"); answer.add("containerCount"); answer.add("containers"); answer.add("fileConfigurations"); } else if (clazz.getSimpleName().equals("Version")) { answer.add("id"); answer.add("defaultVersion"); } return answer; }
From source file:it.sample.parser.util.CommonsUtil.java
/** * Metodo di utilita' che copia i campi non nulli della classe sorgente in quelli della classe di destinazione * /* www. j a va 2 s . com*/ * @param source * @param destination */ public static <K, T> void copyNotNullProperties(K source, T destination) { PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(source); if (descriptors != null) { for (PropertyDescriptor descriptor : descriptors) { try { String propertyName = descriptor.getName(); Field field = getDeclaredField(propertyName, source.getClass()); if (field != null && field.getAnnotation(IgnoreField.class) == null) { boolean wasAccessible = field.isAccessible(); field.setAccessible(true); if (PropertyUtils.getReadMethod(descriptor) != null) { Object val = PropertyUtils.getSimpleProperty(source, propertyName); if (val != null && descriptor.getWriteMethod() != null) { PropertyUtils.setProperty(destination, propertyName, val); } } field.setAccessible(wasAccessible); } } catch (Exception e) { e.printStackTrace(); } } } }
From source file:net.solarnetwork.node.util.ClassUtils.java
/** * Get a Map of non-null <em>simple</em> bean properties for an object. * //from w ww .j a v a 2s. com * @param o * the object to inspect * @param ignore * a set of property names to ignore (optional) * @return Map (never <em>null</em>) * @since 1.1 */ public static Map<String, Object> getSimpleBeanProperties(Object o, Set<String> ignore) { if (ignore == null) { ignore = DEFAULT_BEAN_PROP_NAME_IGNORE; } Map<String, Object> result = new LinkedHashMap<String, Object>(); BeanWrapper bean = new BeanWrapperImpl(o); PropertyDescriptor[] props = bean.getPropertyDescriptors(); for (PropertyDescriptor prop : props) { if (prop.getReadMethod() == null) { continue; } String propName = prop.getName(); if (ignore != null && ignore.contains(propName)) { continue; } Class<?> propType = bean.getPropertyType(propName); if (!(propType.isPrimitive() || propType.isEnum() || String.class.isAssignableFrom(propType) || Number.class.isAssignableFrom(propType) || Character.class.isAssignableFrom(propType) || Byte.class.isAssignableFrom(propType) || Date.class.isAssignableFrom(propType))) { continue; } Object propValue = bean.getPropertyValue(propName); if (propValue == null) { continue; } if (propType.isEnum()) { propValue = propValue.toString(); } else if (Date.class.isAssignableFrom(propType)) { propValue = ((Date) propValue).getTime(); } result.put(propName, propValue); } return result; }
From source file:com.github.hateoas.forms.spring.uber.UberUtils.java
/** * Recursively converts object to nodes of uber data. * * @param objectNode to append to//from www . j a v a2s . c o m * @param object to convert */ public static void toUberData(AbstractUberNode objectNode, Object object) { Set<String> filtered = FILTER_RESOURCE_SUPPORT; if (object == null) { return; } try { // TODO: move all returns to else branch of property descriptor handling if (object instanceof Resource) { Resource<?> resource = (Resource<?>) object; objectNode.addLinks(resource.getLinks()); toUberData(objectNode, resource.getContent()); return; } else if (object instanceof Resources) { Resources<?> resources = (Resources<?>) object; // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar objectNode.addLinks(resources.getLinks()); Collection<?> content = resources.getContent(); toUberData(objectNode, content); return; } else if (object instanceof ResourceSupport) { ResourceSupport resource = (ResourceSupport) object; objectNode.addLinks(resource.getLinks()); // wrap object attributes below to avoid endless loop } else if (object instanceof Collection) { Collection<?> collection = (Collection<?>) object; for (Object item : collection) { // TODO name must be repeated for each collection item UberNode itemNode = new UberNode(); objectNode.addData(itemNode); toUberData(itemNode, item); // toUberData(objectNode, item); } return; } if (object instanceof Map) { Map<?, ?> map = (Map<?, ?>) object; for (Entry<?, ?> entry : map.entrySet()) { String key = entry.getKey().toString(); Object content = entry.getValue(); Object value = getContentAsScalarValue(content); UberNode entryNode = new UberNode(); objectNode.addData(entryNode); entryNode.setName(key); if (value != null) { entryNode.setValue(value); } else { toUberData(entryNode, content); } } } else { PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(object);// BeanUtils // .getPropertyDescriptors(bean.getClass()); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String name = propertyDescriptor.getName(); if (filtered.contains(name)) { continue; } UberNode propertyNode = new UberNode(); Object content = propertyDescriptor.getReadMethod().invoke(object); Object value = getContentAsScalarValue(content); propertyNode.setName(name); objectNode.addData(propertyNode); if (value != null) { // for each scalar property of a simple bean, add valuepair nodes to data propertyNode.setValue(value); } else { toUberData(propertyNode, content); } } } } catch (Exception ex) { throw new RuntimeException("failed to transform object " + object, ex); } }
From source file:org.zht.framework.util.ZBeanUtil.java
private static void copy(Object source, Object target, Boolean ignorNull, Class<?> editable, String... ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); }// ww w. j ava2s . co m actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null); for (PropertyDescriptor targetPd : targetPds) { Method writeMethod = targetPd.getWriteMethod(); if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null) { Method readMethod = sourcePd.getReadMethod(); if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if (ignorNull != null && ignorNull) { if (value != null && (!"[]".equals(value.toString()))) {// ? if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } else { if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } } } }
From source file:org.shept.util.BeanUtilsExtended.java
/** * Merge the property values of the given source bean into the given target bean. * <p>Note: Only not-null values are merged into the given target bean. * Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * @param source the source bean//from w w w .j a va 2s . c o m * @param target the target bean * @param editable the class (or interface) to restrict property setting to * @param ignoreProperties array of property names to ignore * @throws BeansException if the copying failed * @see BeanWrapper */ private static void mergeProperties(Object source, Object target, Class<?> editable, String[] ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); } actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null; for (PropertyDescriptor targetPd : targetPds) { if (targetPd.getWriteMethod() != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null && sourcePd.getReadMethod() != null) { try { Method readMethod = sourcePd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if (value != null) { Method writeMethod = targetPd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } catch (Throwable ex) { throw new FatalBeanException("Could not copy properties from source to target", ex); } } } } }
From source file:cn.fql.utility.ClassUtility.java
/** * Import data to this object from input Map * * @param obj object// w ww . ja v a2 s . c om * @param values <code>values</code> */ public static void importValueFromMap(Object obj, Map values) { if (values != null) { PropertyDescriptor[] pds; try { pds = exportPropertyDesc(obj.getClass()); if (pds != null && pds.length > 0) { Set keySet = values.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String name = (String) it.next(); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; if (pd.getName().equals(name)) { Method setter = pd.getWriteMethod(); if (setter != null) { Object[] params = { values.get(name) }; setter.invoke(obj, params); } break; } } } } } catch (Exception e) { System.out.println(e.getMessage()); } } }
From source file:de.micromata.genome.util.bean.PropertyDescriptorUtils.java
/** * Find anotation first on getter than from field. * * @param <T> the generic type//from www .j ava2 s . c o m * @param beanClazz the bean clazz * @param pd the pd * @param anotclass the anotclass * @return the t */ public static <T extends Annotation> T findAnotation(Class<?> beanClazz, PropertyDescriptor pd, Class<T> anotclass) { Method rm = pd.getReadMethod(); if (rm != null) { T anot = rm.getAnnotation(anotclass); if (anot != null) { return anot; } } Field field = PrivateBeanUtils.findField(beanClazz, pd.getName()); if (field == null) { return null; } T anot = field.getAnnotation(anotclass); return anot; }