List of usage examples for java.beans PropertyDescriptor getReadMethod
public synchronized Method getReadMethod()
From source file:com.bstek.dorado.idesupport.template.RuleTemplate.java
private static void applyProperties(Object source, Object target) throws Exception { for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(target)) { if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) { applyProperty(source, target, propertyDescriptor.getName()); }/*from w w w. ja v a2s. c o m*/ } }
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) *///from ww w .j av a 2 s .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:com.github.dozermapper.core.util.ReflectionUtils.java
/** * There are some nasty bugs for introspection with generics. This method addresses those nasty bugs and tries to find proper methods if available * http://bugs.sun.com/view_bug.do?bug_id=6788525 * http://bugs.sun.com/view_bug.do?bug_id=6528714 * * @param clazz type to work on//from w ww . j a va2s .c o m * @param descriptor property pair (get/set) information * @return descriptor */ private static PropertyDescriptor fixGenericDescriptor(Class<?> clazz, PropertyDescriptor descriptor) { Method readMethod = descriptor.getReadMethod(); if (readMethod != null && (readMethod.isBridge() || readMethod.isSynthetic())) { String propertyName = descriptor.getName(); //capitalize the first letter of the string; String baseName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); String setMethodName = "set" + baseName; String getMethodName = "get" + baseName; Method getMethod = findPreferablyNonSyntheticMethod(getMethodName, clazz); Method setMethod = findPreferablyNonSyntheticMethod(setMethodName, clazz); try { return new PropertyDescriptor(propertyName, getMethod, setMethod); } catch (IntrospectionException e) { //move on } } return descriptor; }
From source file:nl.strohalm.cyclos.utils.EntityHelper.java
/** * Returns a Map with basic properties for the given entity */// w ww.jav a2s . c o m public static Map<String, PropertyDescriptor> propertyDescriptorsFor(final Entity entity) { final Class<? extends Entity> clazz = getRealClass(entity); SortedMap<String, PropertyDescriptor> properties = cachedPropertiesByClass.get(clazz); if (properties == null) { properties = new TreeMap<String, PropertyDescriptor>(); final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(clazz); for (final PropertyDescriptor descriptor : propertyDescriptors) { final String name = descriptor.getName(); boolean ok = name.equals("id"); if (!ok) { final Method readMethod = descriptor.getReadMethod(); if (readMethod != null) { final Class<?> declaringClass = readMethod.getDeclaringClass(); ok = !declaringClass.equals(Entity.class) && !declaringClass.equals(CustomFieldsContainer.class); } } if (ok) { properties.put(name, descriptor); } } properties = Collections.unmodifiableSortedMap(properties); cachedPropertiesByClass.put(clazz, properties); } return properties; }
From source file:org.bibsonomy.layout.util.JabRefModelConverter.java
/** * Converts a BibSonomy post into a JabRef BibtexEntry * // w w w .j a va 2s . co m * @param post * @param urlGen * - the URLGenerator to create the biburl-field * @return */ public static BibtexEntry convertPost(final Post<? extends Resource> post, URLGenerator urlGen) { try { /* * what we have */ final BibTex bibtex = (BibTex) post.getResource(); /* * what we want */ final BibtexEntry entry = new BibtexEntry(); /* * each entry needs an ID (otherwise we get a NPE) ... let JabRef * generate it */ /* * we use introspection to get all fields ... */ final BeanInfo info = Introspector.getBeanInfo(bibtex.getClass()); final PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); /* * iterate over all properties */ for (final PropertyDescriptor pd : descriptors) { final Method getter = pd.getReadMethod(); // loop over all String attributes final Object o = getter.invoke(bibtex, (Object[]) null); if (String.class.equals(pd.getPropertyType()) && (o != null) && !JabRefModelConverter.EXCLUDE_FIELDS.contains(pd.getName())) { final String value = ((String) o); if (present(value)) entry.setField(pd.getName().toLowerCase(), value); } } /* * convert entry type (Is never null but getType() returns null for * unknown types and JabRef knows less types than we.) * * FIXME: a nicer solution would be to implement the corresponding * classes for the missing entrytypes. */ final BibtexEntryType entryType = BibtexEntryType.getType(bibtex.getEntrytype()); entry.setType(entryType == null ? BibtexEntryType.OTHER : entryType); if (present(bibtex.getMisc()) || present(bibtex.getMiscFields())) { // parse the misc fields and loop over them bibtex.parseMiscField(); if (bibtex.getMiscFields() != null) for (final String key : bibtex.getMiscFields().keySet()) { if ("id".equals(key)) { // id is used by jabref entry.setField("misc_id", bibtex.getMiscField(key)); continue; } if (key.startsWith("__")) // ignore fields starting with // __ - jabref uses them for // control continue; entry.setField(key, bibtex.getMiscField(key)); } } final String month = bibtex.getMonth(); if (present(month)) { /* * try to convert the month abbrev like JabRef does it */ final String longMonth = Globals.MONTH_STRINGS.get(month); if (present(longMonth)) { entry.setField("month", longMonth); } else { entry.setField("month", month); } } final String bibAbstract = bibtex.getAbstract(); if (present(bibAbstract)) entry.setField("abstract", bibAbstract); /* * concatenate tags using the JabRef keyword separator */ final Set<Tag> tags = post.getTags(); final StringBuffer tagsBuffer = new StringBuffer(); for (final Tag tag : tags) { tagsBuffer.append(tag.getName() + jabRefKeywordSeparator); } /* * remove last separator */ if (!tags.isEmpty()) { tagsBuffer.delete(tagsBuffer.lastIndexOf(jabRefKeywordSeparator), tagsBuffer.length()); } final String tagsBufferString = tagsBuffer.toString(); if (present(tagsBufferString)) entry.setField(BibTexUtils.ADDITIONAL_MISC_FIELD_KEYWORDS, tagsBufferString); // set groups - will be used in jabref when exporting to bibsonomy if (present(post.getGroups())) { final Set<Group> groups = post.getGroups(); final StringBuffer groupsBuffer = new StringBuffer(); for (final Group group : groups) groupsBuffer.append(group.getName() + " "); final String groupsBufferString = groupsBuffer.toString().trim(); if (present(groupsBufferString)) entry.setField("groups", groupsBufferString); } // set comment + description final String description = post.getDescription(); if (present(description)) { entry.setField(BibTexUtils.ADDITIONAL_MISC_FIELD_DESCRIPTION, post.getDescription()); entry.setField("comment", post.getDescription()); } if (present(post.getDate())) { entry.setField("added-at", sdf.format(post.getDate())); } if (present(post.getChangeDate())) { entry.setField("timestamp", sdf.format(post.getChangeDate())); } if (present(post.getUser())) entry.setField("username", post.getUser().getName()); // set URL to bibtex version of this entry (bibrecord = ...) entry.setField(BibTexUtils.ADDITIONAL_MISC_FIELD_BIBURL, urlGen.getPublicationUrl(bibtex, post.getUser()).toString()); return entry; } catch (final Exception e) { log.error("Could not convert BibSonomy post into a JabRef BibTeX entry.", e); } return null; }
From source file:com.ksmpartners.ernie.util.TestUtil.java
/** * Checks equality of two objects based on the equality of their fields, items, or .equals() method. * @param obj1/* www.jav a2 s.c o m*/ * @param obj2 * @return */ public static <T> boolean equal(T obj1, T obj2) { if (obj1 == null || obj2 == null) { // If they're both null, we call this equal if (obj1 == null && obj2 == null) return true; else return false; } if (!obj1.getClass().equals(obj2.getClass())) return false; if (obj1.equals(obj2)) return true; List<Pair> vals = new ArrayList<Pair>(); // If obj1 and obj2 are Collections, get the objects in them if (Collection.class.isAssignableFrom(obj1.getClass())) { Collection c1 = (Collection) obj1; Collection c2 = (Collection) obj2; if (c1.size() != c2.size()) return false; Iterator itr1 = c1.iterator(); Iterator itr2 = c2.iterator(); while (itr1.hasNext() && itr2.hasNext()) { vals.add(new Pair(itr1.next(), itr2.next())); } } // Get field values from obj1 and obj2 PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj1); for (PropertyDescriptor property : properties) { // ignore getClass() and isEmpty() if (property.getName().equals("class") || property.getName().equals("empty")) continue; Object val1 = invokeMethod(obj1, property.getReadMethod(), null, property.getName()); Object val2 = invokeMethod(obj2, property.getReadMethod(), null, property.getName()); vals.add(new Pair(val1, val2)); } if (vals.isEmpty()) return false; for (Pair pair : vals) { if (!equal(pair.left, pair.right)) return false; } return true; }
From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java
/** * this is Java Reflections translation method doing the magic where JAXB cannot * it is type independent as long as it is a valid java object * it cannot be an interface, abstract class and cannot use generics * /*from w w w. jav a 2 s . c om*/ * @param <T> * @param sourceClass - type of the source object * @param destClass - type of destination object * @param source - source object itself * @return - translated destination object */ public static <T> T transposeModel(Class sourceClass, Class<T> destClass, Object source) { Object destInstance = null; try { destInstance = ConstructorUtils.invokeConstructor(destClass, null); BeanInfo destInfo = Introspector.getBeanInfo(destClass); PropertyDescriptor[] destProps = destInfo.getPropertyDescriptors(); BeanInfo sourceInfo = Introspector.getBeanInfo(sourceClass, Object.class); PropertyDescriptor[] sourceProps = sourceInfo.getPropertyDescriptors(); for (PropertyDescriptor sourceProp : sourceProps) { String name = sourceProp.getName(); Method getter = sourceProp.getReadMethod(); Class<?> sType; try { sType = sourceProp.getPropertyType(); } catch (NullPointerException ex) { System.err .println("The type of source field cannot be determined, field skipped, name: " + name); continue; } Object sValue; try { sValue = getter.invoke(source); } catch (NullPointerException ex) { System.err.println("Cannot obtain the value from field, field skipped, name: " + name); continue; } for (PropertyDescriptor destProp : destProps) { if (destProp.getName().equals(name)) { if (assignPropertyValue(sourceProp, sValue, destProp, destInstance)) System.out.println( "Destination property assigned, source name: " + name + ", type: " + sType); else System.err.println( "Failed to assign property, source name: " + name + ", type: " + sType); break; } } } } catch (InvocationTargetException | IntrospectionException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException | InstantiationException ex) { Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex); } return destClass.cast(destInstance); }
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 w w . j a v a 2 s . c om * @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:es.logongas.ix3.util.ReflectionUtil.java
/** * Obtiene el valor de la propiedad de un Bean * * @param obj El objeto Bean/* w w w .j ava 2 s .c om*/ * @param propertyName El nombre de la propiedad. Se permiten * "subpropiedades" separadas por "." * @return El valor de la propiedad */ static public Object getValueFromBean(Object obj, String propertyName) { try { Object value; BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); if ((propertyName == null) || (propertyName.trim().isEmpty())) { throw new RuntimeException("El parametro propertyName no puede ser null o estar vacio"); } String leftPropertyName; //El nombre de la propiedad antes del primer punto String rigthPropertyName; //El nombre de la propiedad antes del primer punto int indexPoint = propertyName.indexOf("."); if (indexPoint < 0) { leftPropertyName = propertyName; rigthPropertyName = null; } else if ((indexPoint > 0) && (indexPoint < (propertyName.length() - 1))) { leftPropertyName = propertyName.substring(0, indexPoint); rigthPropertyName = propertyName.substring(indexPoint + 1); } else { throw new RuntimeException("El punto no puede estar ni al principio ni al final"); } Method readMethod = null; for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals(leftPropertyName)) { readMethod = propertyDescriptor.getReadMethod(); } } if (readMethod == null) { throw new RuntimeException("No existe la propiedad:" + leftPropertyName); } if (rigthPropertyName != null) { Object valueProperty = readMethod.invoke(obj); value = getValueFromBean(valueProperty, rigthPropertyName); } else { value = readMethod.invoke(obj); } return value; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:net.mojodna.searchable.util.SearchableUtils.java
/** * Generate a list of field names for a given property. * //from www . ja v a 2 s. c om * @param descriptor Property descriptor. * @return Collection of field names. */ public static final Collection<String> getFieldnames(final PropertyDescriptor descriptor) { final Collection<String> fieldnames = new LinkedList<String>(); String fieldname = descriptor.getName(); for (final Class<? extends Annotation> annotationClass : Searchable.INDEXING_ANNOTATIONS) { final Annotation annotation = AnnotationUtils.getAnnotation(descriptor.getReadMethod(), annotationClass); if (annotation instanceof Searchable.Indexed) { final Searchable.Indexed i = (Searchable.Indexed) annotation; if (StringUtils.isNotBlank(i.name())) fieldname = i.name(); // add any aliases fieldnames.addAll(Arrays.asList(i.aliases())); } else if (annotation instanceof Searchable.Stored) { final Searchable.Stored s = (Searchable.Stored) annotation; if (StringUtils.isNotBlank(s.name())) fieldname = s.name(); // add any aliases fieldnames.addAll(Arrays.asList(s.aliases())); } else if (annotation instanceof Searchable.Sortable) { final Searchable.Sortable s = (Sortable) annotation; if (StringUtils.isNotBlank(s.name())) fieldname = s.name(); } } // add the default field name fieldnames.add(fieldname); return fieldnames; }