List of usage examples for java.beans Introspector getBeanInfo
public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException
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; }/* w ww. java2 s . 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:QueryRunner.java
/** * Fill the <code>PreparedStatement</code> replacement parameters with the * given object's bean property values.//from w w w . j av a2 s .c om * * @param stmt * PreparedStatement to fill * @param bean * a JavaBean object * @param propertyNames * an ordered array of property names (these should match the * getters/setters); this gives the order to insert values in the * statement * @throws SQLException * if a database access error occurs */ public void fillStatementWithBean(PreparedStatement stmt, Object bean, String[] propertyNames) throws SQLException { PropertyDescriptor[] descriptors; try { descriptors = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors(); } catch (IntrospectionException e) { throw new RuntimeException("Couldn't introspect bean " + bean.getClass().toString(), e); } PropertyDescriptor[] sorted = new PropertyDescriptor[propertyNames.length]; for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; if (propertyName == null) { throw new NullPointerException("propertyName can't be null: " + i); } boolean found = false; for (int j = 0; j < descriptors.length; j++) { PropertyDescriptor descriptor = descriptors[j]; if (propertyName.equals(descriptor.getName())) { sorted[i] = descriptor; found = true; break; } } if (!found) { throw new RuntimeException("Couldn't find bean property: " + bean.getClass() + " " + propertyName); } } fillStatementWithBean(stmt, bean, sorted); }
From source file:com.datatorrent.stram.appdata.AppDataPushAgent.java
private JSONObject extractFields(Object o) { List<Field> fields; Map<String, Method> methods; if (cacheFields.containsKey(o.getClass())) { fields = cacheFields.get(o.getClass()); } else {//from ww w . j a v a2 s . com fields = new ArrayList<Field>(); for (Class<?> c = o.getClass(); c != Object.class; c = c.getSuperclass()) { Field[] declaredFields = c.getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); AutoMetric rfa = field.getAnnotation(AutoMetric.class); if (rfa != null) { field.setAccessible(true); try { fields.add(field); } catch (Exception ex) { LOG.debug("Error extracting fields for app data: {}. Ignoring.", ex.getMessage()); } } } } cacheFields.put(o.getClass(), fields); } JSONObject result = new JSONObject(); for (Field field : fields) { try { result.put(field.getName(), field.get(o)); } catch (Exception ex) { // ignore } } if (cacheGetMethods.containsKey(o.getClass())) { methods = cacheGetMethods.get(o.getClass()); } else { methods = new HashMap<String, Method>(); try { BeanInfo info = Introspector.getBeanInfo(o.getClass()); for (PropertyDescriptor pd : info.getPropertyDescriptors()) { Method method = pd.getReadMethod(); if (pd.getReadMethod() != null) { AutoMetric rfa = method.getAnnotation(AutoMetric.class); if (rfa != null) { methods.put(pd.getName(), method); } } } } catch (IntrospectionException ex) { // ignore } cacheGetMethods.put(o.getClass(), methods); } for (Map.Entry<String, Method> entry : methods.entrySet()) { try { result.put(entry.getKey(), entry.getValue().invoke(o)); } catch (Exception ex) { // ignore } } return result; }
From source file:com.palantir.ptoss.cinch.core.BindingContext.java
private Map<String, ObjectFieldMethod> indexBindableProperties(Function<PropertyDescriptor, Method> methodFn) throws IntrospectionException { final Map<ObjectFieldMethod, String> getterOfms = Maps.newHashMap(); for (Field field : Sets.newHashSet(bindableModels.values())) { BeanInfo beanInfo = Introspector.getBeanInfo(field.getType()); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : props) { Method method = methodFn.apply(descriptor); if (method == null) { continue; }/*from w w w . ja v a2s. c o m*/ BindableModel model = getFieldObject(field, BindableModel.class); getterOfms.put(new ObjectFieldMethod(model, field, method), descriptor.getName()); } } return dotIndex(getterOfms.keySet(), ObjectFieldMethod.TO_FIELD_NAME, Functions.forMap(getterOfms)); }
From source file:com.liusoft.dlog4j.search.SearchProxy.java
/** * ?//from w w w . jav a 2 s .co m * @param obj * @param field * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SecurityException * @throws NoSuchFieldException * @throws IntrospectionException */ private static Class getNestedPropertyType(Object obj, String field) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException, IntrospectionException { StringTokenizer st = new StringTokenizer(field, "."); Class nodeClass = obj.getClass(); while (st.hasMoreElements()) { String f = st.nextToken(); PropertyDescriptor[] props = Introspector.getBeanInfo(nodeClass).getPropertyDescriptors(); for (int i = 0; i < props.length; i++) { if (props[i].getName().equals(f)) { nodeClass = props[i].getPropertyType(); continue; } } } return nodeClass; }
From source file:es.logongas.ix3.util.ReflectionUtil.java
/** * Establecer el valor en un bena/* ww w . jav a 2s . c om*/ * * @param obj El objeto al que se establece el valor * @param propertyName El nombre de la propieda a establecer el valor. Se * permiten "subpropiedades" separadas por "." * @param value El valor a establecer. */ static public void setValueToBean(Object obj, String propertyName, Object value) { try { if ((propertyName == null) || (propertyName.trim().isEmpty())) { throw new RuntimeException("El parametro propertyName no puede ser null o estar vacio"); } if (obj == null) { throw new RuntimeException("El parametro obj no puede ser null"); } BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); 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; Method writeMethod = null; for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals(leftPropertyName)) { readMethod = propertyDescriptor.getReadMethod(); writeMethod = propertyDescriptor.getWriteMethod(); } } if (rigthPropertyName != null) { if (readMethod == null) { throw new RuntimeException("No existe la propiedad de lectura:" + leftPropertyName); } Object valueProperty = readMethod.invoke(obj); setValueToBean(valueProperty, rigthPropertyName, value); } else { if (writeMethod == null) { throw new RuntimeException("No existe la propiedad de escritura:" + leftPropertyName); } writeMethod.invoke(obj, new Object[] { value }); } } catch (Exception ex) { throw new RuntimeException("obj:" + obj + " propertyName=" + propertyName + " value=" + value, ex); } }
From source file:springfox.documentation.spring.web.readers.parameter.ModelAttributeParameterExpander.java
@VisibleForTesting BeanInfo getBeanInfo(Class<?> clazz) throws IntrospectionException { return Introspector.getBeanInfo(clazz); }
From source file:no.sesat.search.datamodel.BeanDataObjectInvocationHandler.java
private boolean checkPropertyClass(final Class cls, final Property property) { boolean correct = false; if (property.getValue() == null) { return true; }/*from w w w . j a v a2 s. c o m*/ try { PropertyDescriptor[] descriptors = Introspector.getBeanInfo(cls).getPropertyDescriptors(); for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getName().equals(property.getName())) { final Class<?> propertyType = property.getValue().getClass().equals(MapDataObjectSupport.class) ? Map.class : property.getValue().getClass(); correct |= descriptor.getPropertyType() == null || descriptor.getPropertyType().isAssignableFrom(propertyType); break; } } } catch (IntrospectionException e) { /* Do nothing, return value already set */ } return correct; }
From source file:org.jaffa.soa.dataaccess.TransformerUtils.java
/** * Display the properties of this JavaBean in XML format. * * @param source Javabean who's contents should be printed * @return XML formatted string of this beans properties and their values *///from w ww.j av a 2s. c o m public static String printXMLGraph(Object source) { StringBuffer out = new StringBuffer(); out.append("<" + source.getClass().getSimpleName() + ">"); try { BeanInfo sInfo = Introspector.getBeanInfo(source.getClass()); PropertyDescriptor[] sDescriptors = sInfo.getPropertyDescriptors(); if (sDescriptors != null && sDescriptors.length != 0) { for (int i = 0; i < sDescriptors.length; i++) { PropertyDescriptor sDesc = sDescriptors[i]; Method sm = sDesc.getReadMethod(); if (sm != null && sDesc.getWriteMethod() != null) { if (!sm.isAccessible()) sm.setAccessible(true); Object sValue = sm.invoke(source, (Object[]) null); out.append("<" + sDesc.getName() + ">"); if (sValue != null && !sm.getReturnType().isArray() && !GraphDataObject.class.isAssignableFrom(sValue.getClass())) { out.append(sValue.toString().trim()); } out.append("</" + sDesc.getName() + ">"); } } } } catch (IllegalAccessException e) { TransformException me = new TransformException(TransformException.ACCESS_ERROR, "???", e.getMessage()); log.error(me.getLocalizedMessage(), e); //throw me; } catch (InvocationTargetException e) { TransformException me = new TransformException(TransformException.INVOCATION_ERROR, "???", e); log.error(me.getLocalizedMessage(), me.getCause()); //throw me; } catch (IntrospectionException e) { TransformException me = new TransformException(TransformException.INTROSPECT_ERROR, "???", e.getMessage()); log.error(me.getLocalizedMessage(), e); //throw me; } out.append("</" + source.getClass().getSimpleName() + ">"); return out.toString(); }
From source file:kg.apc.jmeter.listener.GraphsGeneratorListener.java
/** * Override the setProperty method in order to convert * the original String calcMode property. * This used the locale-dependent display value, so caused * problems when the language was changed. * Note that the calcMode StringProperty is replaced with an IntegerProperty * so the conversion only needs to happen once. *///from w ww . j a v a2s . c o m @Override public void setProperty(JMeterProperty property) { if (property instanceof StringProperty) { final String pn = property.getName(); if (pn.equals("exportMode")) { final Object objectValue = property.getObjectValue(); try { final BeanInfo beanInfo = Introspector.getBeanInfo(this.getClass()); final ResourceBundle rb = (ResourceBundle) beanInfo.getBeanDescriptor() .getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE); for (Enum<ExportMode> e : ExportMode.values()) { final String propName = e.toString(); if (objectValue.equals(rb.getObject(propName))) { final int tmpMode = e.ordinal(); if (log.isDebugEnabled()) { log.debug("Converted " + pn + "=" + objectValue + " to mode=" + tmpMode + " using Locale: " + rb.getLocale()); } super.setProperty(pn, tmpMode); return; } } log.warn("Could not convert " + pn + "=" + objectValue + " using Locale: " + rb.getLocale()); } catch (IntrospectionException e) { log.error("Could not find BeanInfo", e); } } } super.setProperty(property); }