List of usage examples for java.beans PropertyDescriptor getName
public String getName()
From source file:com.swingtech.commons.testing.JavaBeanTester.java
/** * Tests the get/set methods of the specified class. * //from w w w . j a v a2s . co m * @param <T> the type parameter associated with the class under test * @param clazz the Class under test * @param skipThese the names of any properties that should not be tested * @throws IntrospectionException thrown if the Introspector.getBeanInfo() method throws this exception * for the class under test */ public static <T> void test(final Class<T> clazz, final String... skipThese) throws IntrospectionException { final PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); nextProp: for (PropertyDescriptor prop : props) { // Check the list of properties that we don't want to test for (String skipThis : skipThese) { if (skipThis.equals(prop.getName())) { continue nextProp; } } final Method getter = prop.getReadMethod(); final Method setter = prop.getWriteMethod(); if (getter != null && setter != null) { // We have both a get and set method for this property final Class<?> returnType = getter.getReturnType(); final Class<?>[] params = setter.getParameterTypes(); if (params.length == 1 && params[0] == returnType) { // The set method has 1 argument, which is of the same type as the return type of the get method, so we can test this property try { // Build a value of the correct type to be passed to the set method Object value = buildValue(returnType); // Build an instance of the bean that we are testing (each property test gets a new instance) T bean = clazz.newInstance(); // Call the set method, then check the same value comes back out of the get method setter.invoke(bean, value); final Object expectedValue = value; final Object actualValue = getter.invoke(bean); assertEquals(String.format("Failed while testing property %s", prop.getName()), expectedValue, actualValue); } catch (Exception ex) { fail(String.format("An exception was thrown while testing the property %s: %s", prop.getName(), ex.toString())); } } } } }
From source file:org.caratarse.auth.model.util.BeanUtils.java
/** * Copy the not-null property values of the given source bean into the given target bean. * <p>//from w ww . j a v a 2 s . co m * 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 * @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 copyNotNullProperties(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 = org.springframework.beans.BeanUtils.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 = org.springframework.beans.BeanUtils .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 (value == null) { continue; } 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:net.mojodna.searchable.util.SearchableUtils.java
/** * @param clazz/*w w w . jav a 2 s . c o m*/ * @param propertyName * @return Return type. */ public static final Class<?> getReturnType(final Class<?> clazz, final String propertyName) { final String key = clazz.getName() + "#" + propertyName; if (returnTypeCache.containsKey(key)) { return returnTypeCache.get(key); } if (returnTypeMissCache.containsKey(key)) { return null; } for (final PropertyDescriptor d : PropertyUtils.getPropertyDescriptors(clazz)) { if (d.getName().equals(propertyName)) { final Class<?> returnType = d.getReadMethod().getReturnType(); returnTypeCache.put(key, returnType); return returnType; } } returnTypeMissCache.put(key, key); return null; }
From source file:com.espertech.esper.event.bean.PropertyHelper.java
private static void addIntrospectPropertiesWritable(Class clazz, Set<WriteablePropertyDescriptor> result) { PropertyDescriptor properties[] = introspect(clazz); for (int i = 0; i < properties.length; i++) { PropertyDescriptor property = properties[i]; String propertyName = property.getName(); Method writeMethod = property.getWriteMethod(); if (writeMethod == null) { continue; }/*from w ww.jav a 2 s .c om*/ result.add( new WriteablePropertyDescriptor(propertyName, writeMethod.getParameterTypes()[0], writeMethod)); } }
From source file:net.sf.ij_plugins.util.DialogUtil.java
/** * Utility to automatically create ImageJ's GenericDialog for editing bean properties. It uses BeanInfo to extract * display names for each field. If a fields type is not supported irs name will be displayed with a tag * "[Unsupported type: class_name]"./*www . ja v a 2 s. com*/ * * @param bean * @return <code>true</code> if user closed bean dialog using OK button, <code>false</code> otherwise. */ static public boolean showGenericDialog(final Object bean, final String title) { final BeanInfo beanInfo; try { beanInfo = Introspector.getBeanInfo(bean.getClass()); } catch (IntrospectionException e) { throw new IJPluginsRuntimeException("Error extracting bean info.", e); } final GenericDialog genericDialog = new GenericDialog(title); // Create generic dialog fields for each bean's property final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); try { for (int i = 0; i < propertyDescriptors.length; i++) { final PropertyDescriptor pd = propertyDescriptors[i]; final Class type = pd.getPropertyType(); if (type.equals(Class.class) && "class".equals(pd.getName())) { continue; } final Object o = PropertyUtils.getSimpleProperty(bean, pd.getName()); if (type.equals(Boolean.TYPE)) { boolean value = ((Boolean) o).booleanValue(); genericDialog.addCheckbox(pd.getDisplayName(), value); } else if (type.equals(Integer.TYPE)) { int value = ((Integer) o).intValue(); genericDialog.addNumericField(pd.getDisplayName(), value, 0); } else if (type.equals(Float.TYPE)) { double value = ((Float) o).doubleValue(); genericDialog.addNumericField(pd.getDisplayName(), value, 6, 10, ""); } else if (type.equals(Double.TYPE)) { double value = ((Double) o).doubleValue(); genericDialog.addNumericField(pd.getDisplayName(), value, 6, 10, ""); } else { genericDialog.addMessage(pd.getDisplayName() + "[Unsupported type: " + type + "]"); } } } catch (IllegalAccessException e) { throw new IJPluginsRuntimeException(e); } catch (InvocationTargetException e) { throw new IJPluginsRuntimeException(e); } catch (NoSuchMethodException e) { throw new IJPluginsRuntimeException(e); } // final Panel helpPanel = new Panel(); // helpPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0)); // final Button helpButton = new Button("Help"); //// helpButton.addActionListener(this); // helpPanel.add(helpButton); // genericDialog.addPanel(helpPanel, GridBagConstraints.EAST, new Insets(15,0,0,0)); // Show modal dialog genericDialog.showDialog(); if (genericDialog.wasCanceled()) { return false; } // Read fields from generic dialog into bean's properties. try { for (int i = 0; i < propertyDescriptors.length; i++) { final PropertyDescriptor pd = propertyDescriptors[i]; final Class type = pd.getPropertyType(); final Object propertyValue; if (type.equals(Boolean.TYPE)) { boolean value = genericDialog.getNextBoolean(); propertyValue = Boolean.valueOf(value); } else if (type.equals(Integer.TYPE)) { int value = (int) Math.round(genericDialog.getNextNumber()); propertyValue = new Integer(value); } else if (type.equals(Float.TYPE)) { double value = genericDialog.getNextNumber(); propertyValue = new Float(value); } else if (type.equals(Double.TYPE)) { double value = genericDialog.getNextNumber(); propertyValue = new Double(value); } else { continue; } PropertyUtils.setProperty(bean, pd.getName(), propertyValue); } } catch (IllegalAccessException e) { throw new IJPluginsRuntimeException(e); } catch (InvocationTargetException e) { throw new IJPluginsRuntimeException(e); } catch (NoSuchMethodException e) { throw new IJPluginsRuntimeException(e); } return true; }
From source file:com.espertech.esper.event.bean.PropertyHelper.java
/** * Adds to the given list of property descriptors the properties of the given class * using the Introspector to introspect properties. This also finds array and indexed properties. * @param clazz to introspect/*from ww w .j a v a 2 s . c o m*/ * @param result is the list to add to */ protected static void addIntrospectProperties(Class clazz, List<InternalEventPropDescriptor> result) { PropertyDescriptor properties[] = introspect(clazz); for (int i = 0; i < properties.length; i++) { PropertyDescriptor property = properties[i]; String propertyName = property.getName(); Method readMethod = property.getReadMethod(); EventPropertyType type = EventPropertyType.SIMPLE; if (property instanceof IndexedPropertyDescriptor) { readMethod = ((IndexedPropertyDescriptor) property).getIndexedReadMethod(); type = EventPropertyType.INDEXED; } if (readMethod == null) { continue; } result.add(new InternalEventPropDescriptor(propertyName, readMethod, type)); } }
From source file:net.solarnetwork.node.util.ClassUtils.java
/** * Get a Map of non-null bean properties for an object. * /*from w w w. ja v a2s . com*/ * @param o * the object to inspect * @param ignore * a set of property names to ignore (optional) * @return Map (never null) */ public static Map<String, Object> getBeanProperties(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; } Object propValue = bean.getPropertyValue(propName); if (propValue == null) { continue; } result.put(propName, propValue); } return result; }
From source file:com.gisgraphy.helper.BeanHelper.java
public static String toString(Object current) { if (current == null) { return "null"; }//from ww w .jav a2s . c om final StringBuffer buffer = new StringBuffer(); final String beanName = current.getClass().getSimpleName(); buffer.append(beanName); buffer.append(" { "); String propertyName; Object propertyValue = null; boolean first = true; Exception exception; try { for (final PropertyDescriptor propertyDescriptor : Introspector .getBeanInfo(current.getClass(), Object.class).getPropertyDescriptors()) { exception = null; propertyName = propertyDescriptor.getName(); logger.debug("propertyName=" + propertyName); try { propertyValue = PropertyUtils.getProperty(current, propertyName); } catch (final IllegalAccessException e) { exception = e; } catch (final InvocationTargetException e) { exception = e; } catch (final NoSuchMethodException e) { exception = e; } if (exception != null) { logger.debug("impossible to get value of property " + propertyName + " of bean " + beanName, exception); continue; } if (first) { first = false; } else { buffer.append(", "); } buffer.append(propertyName); buffer.append(':'); buffer.append(propertyValue); } } catch (final IntrospectionException e) { logger.error("impossible to get properties of bean " + beanName, e); } buffer.append(" }"); return buffer.toString(); }
From source file:com.krm.dbaudit.common.utils.Collections3.java
/** * Map JavaBean /* ww w. j a v a 2 s . c o m*/ * @param type ? * @param map ? map * @return ? JavaBean * @throws IntrospectionException ? * @throws IllegalAccessException JavaBean * @throws InstantiationException JavaBean * @throws InvocationTargetException setter */ public static Object convertMap(Class type, Map map) throws IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException { BeanInfo beanInfo = Introspector.getBeanInfo(type); // ? Object obj = type.newInstance(); // JavaBean // JavaBean PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (map.containsKey(propertyName)) { // ??? try ??? Object value = map.get(propertyName); if (propertyName.equals("id") || propertyName.equals("parentId")) { value = Long.valueOf(value.toString()); } if (value instanceof Number) { value = Long.valueOf(value.toString()); } else if (value instanceof Date) { value = (Date) value; } Object[] args = new Object[1]; args[0] = value; descriptor.getWriteMethod().invoke(obj, args); } } return obj; }
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 * //www . j a v a 2s . c o 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(); } } } }