List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:org.bibsonomy.plugin.jabref.util.JabRefModelConverter.java
/** * @param bibtex//from w w w.j a v a2 s .c o m * target object * @param entry * source object * @return list of all copied property names */ public static List<String> copyStringPropertiesToBibsonomyModel(final BibTex bibtex, final BibtexEntry entry) { final List<String> knownFields = new ArrayList<String>(50); final BeanInfo info; try { info = Introspector.getBeanInfo(bibtex.getClass()); } catch (IntrospectionException e) { ExceptionUtils.logErrorAndThrowRuntimeException(log, e, "could not introspect"); return knownFields; } final PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); // set all known properties of the BibTex for (PropertyDescriptor pd : descriptors) { if (String.class.equals(pd.getPropertyType()) == false) { continue; } if (present(entry.getField((pd.getName().toLowerCase()))) && !JabRefModelConverter.EXCLUDE_FIELDS.contains(pd.getName().toLowerCase())) { final Object value = entry.getField(pd.getName().toLowerCase()); try { pd.getWriteMethod().invoke(bibtex, value); } catch (Exception e) { ExceptionUtils.logErrorAndThrowRuntimeException(log, e, "could not convert property " + pd.getName()); return knownFields; } knownFields.add(pd.getName()); } } return knownFields; }
From source file:com.wavemaker.json.type.reflect.ReflectTypeUtils.java
/** * Initializes a TypeDefinition from a given class. The first entry in the return list is the TypeDefinition for the * parameter class; any entries after that (if any) are TypeDefinitions for any other types that were required as * fields for that root TypeDefinition./* w ww.ja va2s .c o m*/ * * @param klass The Class object to describe. * @param typeState The TypeState for the current operation. * @param strict True indicates that processing should stop on ambiguous entries; false indicates that null should * be entered. * @return A list of TypeDefinitions; the first entry is the root (corresponding with the klass parameter), any * other entries in the list were required to describe the root TypeDefinition's fields. The return may also * be null, if sufficient information was not provided to determine the type. */ public static TypeDefinition getTypeDefinition(Type type, TypeState typeState, boolean strict) { Class<?> klass; // we already know about this type; we're done if (typeState.isTypeKnown(ReflectTypeUtils.getTypeName(type))) { return typeState.getType(ReflectTypeUtils.getTypeName(type)); } // if the type is Object, return null, we can't figure out anything more if (type instanceof Class && Object.class.equals(type)) { return null; } // if we don't have enough information, return null if (!strict) { if (type instanceof Class && Map.class.isAssignableFrom((Class<?>) type) && !Properties.class.isAssignableFrom((Class<?>) type)) { if (!JSON.class.isAssignableFrom((Class<?>) type)) { logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type)); } return null; } else if (type instanceof Class && List.class.isAssignableFrom((Class<?>) type)) { if (!JSON.class.isAssignableFrom((Class<?>) type)) { logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type)); } return null; } } TypeDefinition ret; if (type instanceof Class && Properties.class.isAssignableFrom((Class<?>) type)) { MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition(); mtdret.setTypeName(ReflectTypeUtils.getTypeName(type)); mtdret.setShortName(ReflectTypeUtils.getShortName(type)); typeState.addType(mtdret); klass = (Class<?>) type; mtdret.setKlass(klass); TypeDefinition stringType = getTypeDefinition(String.class, typeState, false); mtdret.setKeyFieldDefinition(new GenericFieldDefinition(stringType)); mtdret.setValueFieldDefinition(new GenericFieldDefinition(stringType)); ret = mtdret; } else if (type instanceof Class && JSONUtils.isPrimitive((Class<?>) type)) { PrimitiveReflectTypeDefinition ptret; if (((Class<?>) type).isEnum()) { ptret = new EnumPrimitiveReflectTypeDefinition(); } else { ptret = new PrimitiveReflectTypeDefinition(); } ptret.setTypeName(ReflectTypeUtils.getTypeName(type)); ptret.setShortName(ReflectTypeUtils.getShortName(type)); typeState.addType(ptret); klass = (Class<?>) type; ptret.setKlass(klass); ret = ptret; } else if (type instanceof Class) { klass = (Class<?>) type; if (Collection.class.isAssignableFrom(klass)) { throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass); } else if (klass.isArray()) { throw new WMRuntimeException(MessageResource.JSON_USE_FIELD_FOR_ARRAY, klass); } else if (Map.class.isAssignableFrom(klass)) { throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass); } else if (ClassUtils.isPrimitiveOrWrapper(klass) || CharSequence.class.isAssignableFrom(klass)) { PrimitiveReflectTypeDefinition ptret = new PrimitiveReflectTypeDefinition(); ptret.setTypeName(ReflectTypeUtils.getTypeName(type)); ptret.setShortName(ReflectTypeUtils.getShortName(type)); typeState.addType(ptret); ptret.setKlass(klass); ret = ptret; } else { ObjectReflectTypeDefinition otret = new ObjectReflectTypeDefinition(); otret.setTypeName(ReflectTypeUtils.getTypeName(type)); otret.setShortName(ReflectTypeUtils.getShortName(type)); otret.setKlass(klass); typeState.addType(otret); PropertyUtilsBean pub = ((ReflectTypeState) typeState).getPropertyUtilsBean(); PropertyDescriptor[] pds = pub.getPropertyDescriptors(klass); otret.setFields(new LinkedHashMap<String, FieldDefinition>(pds.length)); for (PropertyDescriptor pd : pds) { if (pd.getName().equals("class")) { continue; } Type paramType; if (pd.getReadMethod() != null) { paramType = pd.getReadMethod().getGenericReturnType(); } else if (pd.getWriteMethod() != null) { paramType = pd.getWriteMethod().getGenericParameterTypes()[0]; } else { logger.warn("No getter in type " + pd.getName()); continue; } otret.getFields().put(pd.getName(), getFieldDefinition(paramType, typeState, strict, pd.getName())); } ret = otret; } } else if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; if (pt.getRawType() instanceof Class && Map.class.isAssignableFrom((Class<?>) pt.getRawType())) { MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition(); mtdret.setTypeName(ReflectTypeUtils.getTypeName(type)); mtdret.setShortName(ReflectTypeUtils.getShortName(type)); typeState.addType(mtdret); Type[] types = pt.getActualTypeArguments(); mtdret.setKeyFieldDefinition(getFieldDefinition(types[0], typeState, strict, null)); mtdret.setValueFieldDefinition(getFieldDefinition(types[1], typeState, strict, null)); mtdret.setKlass((Class<?>) pt.getRawType()); ret = mtdret; } else { throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNRAWTYPE, pt.getOwnerType(), pt); } } else { throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNPARAMTYPE, type, type != null ? type.getClass() : null); } return ret; }
From source file:org.xmlactions.mapping.xml_to_bean.PopulateClassFromXml.java
public static PropertyDescriptor findPropertyDescriptor(Object object, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyDescriptor pd = null; PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(object); for (PropertyDescriptor p : pds) { if (p.getName().equals(name)) { pd = p;/* w ww .java2s. co m*/ break; } } if (pd != null) { log.debug("PropertyDescriptor [" + name + "] - " + " Name:" + pd.getName() + " DisplayName:" + pd.getDisplayName() + " ShortDescription:" + pd.getShortDescription() + " PropertyType:" + pd.getPropertyType() + " ReadMethod:" + pd.getReadMethod() + " WriteMethod:" + pd.getWriteMethod() + " Value:" + pd.getValue(name)); // } else { // log.error("PropertyDescriptor [" + name + // "] - not found in class [" + object.getClass().getName() + "]"); } return pd; }
From source file:org.wildfly.swarm.microprofile.openapi.api.util.MergeUtil.java
/** * Generic merge of two objects of the same type. * @param object1/* ww w .j ava2 s . c o m*/ * @param object2 */ @SuppressWarnings({ "rawtypes" }) public static <T> T mergeObjects(T object1, T object2) { if (object1 == null && object2 != null) { return object2; } if (object1 != null && object2 == null) { return object1; } if (object1 == null && object2 == null) { return null; } // It's uncommon, but in some cases (like Link Parameters or Examples) the values could // be different types. In this case, just take the 2nd one (the override). if (!object1.getClass().equals(object2.getClass())) { return object2; } PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(object1); for (PropertyDescriptor descriptor : descriptors) { if (EXCLUDED_PROPERTIES.contains(descriptor.getName())) { continue; } Class ptype = descriptor.getPropertyType(); if (Map.class.isAssignableFrom(ptype)) { try { Map values1 = (Map) descriptor.getReadMethod().invoke(object1); Map values2 = (Map) descriptor.getReadMethod().invoke(object2); Map newValues = mergeMaps(values1, values2); descriptor.getWriteMethod().invoke(object1, newValues); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } else if (List.class.isAssignableFrom(ptype)) { try { List values1 = (List) descriptor.getReadMethod().invoke(object1); List values2 = (List) descriptor.getReadMethod().invoke(object2); List newValues = mergeLists(values1, values2); descriptor.getWriteMethod().invoke(object1, newValues); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } else if (Constructible.class.isAssignableFrom(ptype)) { try { Object val1 = descriptor.getReadMethod().invoke(object1); Object val2 = descriptor.getReadMethod().invoke(object2); Object newValue = mergeObjects(val1, val2); if (newValue != null) { descriptor.getWriteMethod().invoke(object1, newValue); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } else { try { Object newValue = descriptor.getReadMethod().invoke(object2); if (newValue != null) { descriptor.getWriteMethod().invoke(object1, newValue); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } } return object1; }
From source file:com.ms.commons.summer.web.util.json.JsonBeanUtils.java
/** * Creates a bean from a JSONObject, with the specific configuration. *//*from w w w.ja v a 2 s . c o m*/ public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) { if (jsonObject == null || jsonObject.isNullObject()) { return null; } Class beanClass = jsonConfig.getRootClass(); Map classMap = jsonConfig.getClassMap(); if (beanClass == null) { return toBean(jsonObject); } if (classMap == null) { classMap = Collections.EMPTY_MAP; } Object bean = null; try { if (beanClass.isInterface()) { if (!Map.class.isAssignableFrom(beanClass)) { throw new JSONException("beanClass is an interface. " + beanClass); } else { bean = new HashMap(); } } else { bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject); } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException(e); } Map props = JSONUtils.getProperties(jsonObject); PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter(); for (Iterator entries = jsonObject.names().iterator(); entries.hasNext();) { String name = (String) entries.next(); Class type = (Class) props.get(name); Object value = jsonObject.get(name); if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) { continue; } String key = Map.class.isAssignableFrom(beanClass) && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name : JSONUtils.convertToJavaIdentifier(name, jsonConfig); try { if (Map.class.isAssignableFrom(beanClass)) { // no type info available for conversion if (JSONUtils.isNull(value)) { setProperty(bean, key, value, jsonConfig); } else if (value instanceof JSONArray) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, List.class), jsonConfig); } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(bean, key, null, jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } else { Class targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(targetClass); jsc.setClassMap(classMap); if (targetClass != null) { setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } else { setProperty(bean, key, toBean((JSONObject) value), jsonConfig); } } } else { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key); if (pd != null && pd.getWriteMethod() == null) { log.warn("Property '" + key + "' has no write method. SKIPPED."); continue; } if (pd != null) { Class targetType = pd.getPropertyType(); if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { if (List.class.isAssignableFrom(pd.getPropertyType())) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, pd.getPropertyType()), jsonConfig); } else if (Set.class.isAssignableFrom(pd.getPropertyType())) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, pd.getPropertyType()), jsonConfig); } else { setProperty(bean, key, convertPropertyValueToArray(key, value, targetType, jsonConfig, classMap), jsonConfig); } } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (pd != null) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(bean, key, null, jsonConfig); } else if (!targetType.isInstance(value)) { setProperty(bean, key, morphPropertyValue(key, value, type, targetType), jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } else if (beanClass == null || bean instanceof Map) { setProperty(bean, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass().getName()); } } else { if (jsonConfig.isHandleJettisonSingleElementArray()) { JSONArray array = new JSONArray().element(value, jsonConfig); Class newTargetClass = findTargetClass(key, classMap); newTargetClass = newTargetClass == null ? findTargetClass(name, classMap) : newTargetClass; JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(newTargetClass); jsc.setClassMap(classMap); if (targetType.isArray()) { setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig); } else if (JSONArray.class.isAssignableFrom(targetType)) { setProperty(bean, key, array, jsonConfig); } else if (List.class.isAssignableFrom(targetType) || Set.class.isAssignableFrom(targetType)) { jsc.setCollectionType(targetType); setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig); } else { setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } } else { if (targetType == Object.class) { targetType = findTargetClass(key, classMap); targetType = targetType == null ? findTargetClass(name, classMap) : targetType; } JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(targetType); jsc.setClassMap(classMap); setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(bean, key, null, jsonConfig); } } } else { if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, List.class), jsonConfig); } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (pd != null) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(bean, key, null, jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } else if (beanClass == null || bean instanceof Map) { setProperty(bean, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass().getName()); } } else { if (jsonConfig.isHandleJettisonSingleElementArray()) { Class newTargetClass = findTargetClass(key, classMap); newTargetClass = newTargetClass == null ? findTargetClass(name, classMap) : newTargetClass; JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(newTargetClass); jsc.setClassMap(classMap); setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(bean, key, null, jsonConfig); } } } } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException("Error while setting property=" + name + " type " + type, e); } } return bean; }
From source file:com.thesoftwarefactory.vertx.web.model.Form.java
/** * Build a new Form instance from the specified class * /* ww w .j a va 2 s.c om*/ * @param cls * @param fieldPrefix: if not null, the prefix is prepended to each field name * @return */ public final static <T> Form<T> fromClass(Class<T> cls, String fieldPrefix) { Objects.requireNonNull(cls); Form<T> result = new Form<T>(); if (fieldPrefix != null) { result.fieldPrefix = fieldPrefix; } // discover properties for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(cls)) { if (property.getReadMethod() != null && property.getWriteMethod() != null) { // the property has a getter and setter String fieldName = fieldPrefix != null ? fieldPrefix + property.getName() : property.getName(); result.addField(result.new Field(fieldName, Form.fieldTypefromClass(property.getPropertyType()))); } } return result; }
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 * //from w w w .j a v a 2 s . c o m * @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:jp.co.ctc_g.jfw.core.util.Beans.java
private static boolean writePseudoPropertyValueNamed0(String propertyName, Object bean, Object newValue) { try {/*w ww .j ava 2 s . com*/ PropertyDescriptor pd = findPropertyDescriptorFor(bean.getClass(), propertyName); // ??????? if (pd != null) { Method writer = pd.getWriteMethod(); if (writer != null) { writer.setAccessible(true); writer.invoke(bean, newValue); return true; } else { if (L.isDebugEnabled()) { Map<String, Object> replace = new HashMap<String, Object>(1); replace.put("property", propertyName); L.debug(Strings.substitute(R.getString("D-UTIL#0009"), replace)); } return false; } // ??????? } else { Field f = bean.getClass().getField(propertyName); if (f != null) { f.setAccessible(true); f.set(bean, newValue); return true; } else { if (L.isDebugEnabled()) { Map<String, Object> replace = new HashMap<String, Object>(1); replace.put("property", propertyName); L.debug(Strings.substitute(R.getString("D-UTIL#0010"), replace)); } return false; } } } catch (SecurityException e) { throw new InternalException(Beans.class, "E-UTIL#0010", e); } catch (NoSuchFieldException e) { Map<String, String> replace = new HashMap<String, String>(1); replace.put("property", propertyName); throw new InternalException(Beans.class, "E-UTIL#0011", replace, e); } catch (IllegalArgumentException e) { Map<String, String> replace = new HashMap<String, String>(1); replace.put("property", propertyName); throw new InternalException(Beans.class, "E-UTIL#0012", replace, e); } catch (IllegalAccessException e) { throw new InternalException(Beans.class, "E-UTIL#0013", e); } catch (InvocationTargetException e) { Map<String, String> replace = new HashMap<String, String>(1); replace.put("property", propertyName); replace.put("class", bean.getClass().getName()); throw new InternalException(Beans.class, "E-UTIL#0014", replace, e); } }
From source file:com.fengduo.bee.commons.core.lang.CollectionUtils.java
public static <M> void merge(M original, M destination, List<String> ignore) throws Exception { BeanInfo beanInfo = Introspector.getBeanInfo(original.getClass()); // Iterate over all the attributes for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) { // Only copy writable attributes if (descriptor.getWriteMethod() != null) { Object originalValue = descriptor.getReadMethod().invoke(original); String attributeName = descriptor.getName(); // ignore this values,do'not merge if (ignore != null && !ignore.isEmpty() && ignore.contains(attributeName)) { continue; }/*from w w w . j av a2s. c om*/ Object defaultValue = descriptor.getReadMethod().invoke(destination); // Only copy values values where the destination values is null if (originalValue == null) { descriptor.getWriteMethod().invoke(original, defaultValue); } if (defaultValue instanceof Number && originalValue instanceof Number) { descriptor.getWriteMethod().invoke(original, MathUtils.add((Number) originalValue, (Number) defaultValue)); } } } }
From source file:org.springframework.beans.BeanUtils.java
/** * Obtain a new MethodParameter object for the write method of the * specified property.//from w w w. ja v a 2 s. c o m * @param pd the PropertyDescriptor for the property * @return a corresponding MethodParameter object */ public static MethodParameter getWriteMethodParameter(PropertyDescriptor pd) { if (pd instanceof GenericTypeAwarePropertyDescriptor) { return new MethodParameter(((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodParameter()); } else { Method writeMethod = pd.getWriteMethod(); Assert.state(writeMethod != null, "No write method available"); return new MethodParameter(writeMethod, 0); } }