Example usage for java.beans PropertyEditor getClass

List of usage examples for java.beans PropertyEditor getClass

Introduction

In this page you can find the example usage for java.beans PropertyEditor getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:net.solarnetwork.util.CloningPropertyEditorRegistrar.java

private void registerEditor(PropertyEditorRegistry registry, Map.Entry<?, PropertyEditor> me) {
    PropertyEditor ed = me.getValue();
    Object key = me.getKey();//from  www . jav  a 2s.c  o m
    try {
        Method m = ed.getClass().getMethod("clone", (Class[]) null);
        PropertyEditor copy = (PropertyEditor) m.invoke(ed, (Object[]) null);
        registerValue(registry, copy, key);
    } catch (NoSuchMethodException e) {
        if (lenient) {
            // fall back to non-cloned copy, assume it's thread safe!
            registerValue(registry, ed, key);
        } else {
            throw new RuntimeException(e);
        }
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.springmodules.cache.provider.ehcache.EhCacheFacadeTests.java

public void testGetCachingModelEditor() {
    PropertyEditor editor = cacheFacade.getCachingModelEditor();

    assertNotNull(editor);//  w w w  . j  a  v  a2 s.c om
    assertEquals(ReflectionCacheModelEditor.class, editor.getClass());

    ReflectionCacheModelEditor modelEditor = (ReflectionCacheModelEditor) editor;
    assertEquals(EhCacheCachingModel.class, modelEditor.getCacheModelClass());
    assertNull(modelEditor.getCacheModelPropertyEditors());
}

From source file:org.springmodules.cache.provider.ehcache.EhCacheFacadeTests.java

public void testGetFlushingModelEditor() {
    PropertyEditor editor = cacheFacade.getFlushingModelEditor();

    assertNotNull(editor);/* w ww.  j  av  a2s.com*/
    assertEquals(ReflectionCacheModelEditor.class, editor.getClass());

    ReflectionCacheModelEditor modelEditor = (ReflectionCacheModelEditor) editor;
    assertEquals(EhCacheFlushingModel.class, modelEditor.getCacheModelClass());
    Map propertyEditors = modelEditor.getCacheModelPropertyEditors();
    assertEquals(1, propertyEditors.size());
    assertSame(StringArrayPropertyEditor.class, propertyEditors.get("cacheNames").getClass());
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

/**
 * Convert the given text value using the given property editor.
 * //  www.j a va  2  s  .  co m
 * @param oldValue
 *            the previous value, if available (may be <code>null</code>)
 * @param newTextValue
 *            the proposed text value
 * @param editor
 *            the PropertyEditor to use
 * @return the converted value
 */
private Object doConvertTextValue(Object oldValue, String newTextValue, PropertyEditor editor) {
    try {
        editor.setValue(oldValue);
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call",
                    ex);
        }
        // Swallow and proceed.
    }
    editor.setAsText(newTextValue);
    return editor.getValue();
}

From source file:com.springframework.beans.TypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String),
 * using the given property editor.//from ww w . j  a v a  2s .com
 * @param oldValue the previous value, if available (may be {@code null})
 * @param newValue the proposed new value
 * @param requiredType the type we must convert to
 * (or {@code null} if not known, for example in case of a collection element)
 * @param editor the PropertyEditor to use
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException if type conversion failed
 */
private Object doConvertValue(Object oldValue, Object newValue, Class<?> requiredType, PropertyEditor editor) {
    Object convertedValue = newValue;

    if (editor != null && !(convertedValue instanceof String)) {
        // Not a String -> use PropertyEditor's setValue.
        // With standard PropertyEditors, this will return the very same object;
        // we just want to allow special PropertyEditors to override setValue
        // for type conversion from non-String values to the required type.
        try {
            editor.setValue(convertedValue);
            Object newConvertedValue = editor.getValue();
            if (newConvertedValue != convertedValue) {
                convertedValue = newConvertedValue;
                // Reset PropertyEditor: It already did a proper conversion.
                // Don't use it again for a setAsText call.
                editor = null;
            }
        } catch (Exception ex) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call",
                        ex);
            }
            // Swallow and proceed.
        }
    }

    Object returnValue = convertedValue;

    if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) {
        // Convert String array to a comma-separated String.
        // Only applies if no PropertyEditor converted the String array before.
        // The CSV String will be passed into a PropertyEditor's setAsText method, if any.
        if (logger.isTraceEnabled()) {
            logger.trace("Converting String array to comma-delimited String [" + convertedValue + "]");
        }
        convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue);
    }

    if (convertedValue instanceof String) {
        if (editor != null) {
            // Use PropertyEditor's setAsText in case of a String value.
            if (logger.isTraceEnabled()) {
                logger.trace(
                        "Converting String to [" + requiredType + "] using property editor [" + editor + "]");
            }
            String newTextValue = (String) convertedValue;
            return doConvertTextValue(oldValue, newTextValue, editor);
        } else if (String.class.equals(requiredType)) {
            returnValue = convertedValue;
        }
    }

    return returnValue;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String), using the given property editor.
 * //from   w  w  w .ja  v a2 s.com
 * @param oldValue
 *            the previous value, if available (may be <code>null</code>)
 * @param newValue
 *            the proposed new value
 * @param requiredType
 *            the type we must convert to (or <code>null</code> if not known, for example in case of a collection
 *            element)
 * @param editor
 *            the PropertyEditor to use
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException
 *             if type conversion failed
 */
private Object doConvertValue(Object oldValue, Object newValue, Class<?> requiredType, PropertyEditor editor) {
    Object convertedValue = newValue;
    boolean sharedEditor = false;

    if (editor != null) {
        sharedEditor = this.propertyEditorRegistry.isSharedEditor(editor);
    }

    if (editor != null && !(convertedValue instanceof String)) {
        // Not a String -> use PropertyEditor's setValue.
        // With standard PropertyEditors, this will return the very same object;
        // we just want to allow special PropertyEditors to override setValue
        // for type conversion from non-String values to the required type.
        try {
            Object newConvertedValue;
            if (sharedEditor) {
                // Synchronized access to shared editor instance.
                synchronized (editor) {
                    editor.setValue(convertedValue);
                    newConvertedValue = editor.getValue();
                }
            } else {
                // Unsynchronized access to non-shared editor instance.
                editor.setValue(convertedValue);
                newConvertedValue = editor.getValue();
            }
            if (newConvertedValue != convertedValue) {
                convertedValue = newConvertedValue;
                // Reset PropertyEditor: It already did a proper conversion.
                // Don't use it again for a setAsText call.
                editor = null;
            }
        } catch (Exception ex) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call",
                        ex);
            }
            // Swallow and proceed.
        }
    }

    Object returnValue = convertedValue;

    if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) {
        // Convert String array to a comma-separated String.
        // Only applies if no PropertyEditor converted the String array before.
        // The CSV String will be passed into a PropertyEditor's setAsText method, if any.
        if (logger.isTraceEnabled()) {
            logger.trace("Converting String array to comma-delimited String [" + convertedValue + "]");
        }
        convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue);
    }

    if (convertedValue instanceof String) {
        if (editor != null) {
            // Use PropertyEditor's setAsText in case of a String value.
            if (logger.isTraceEnabled()) {
                logger.trace(
                        "Converting String to [" + requiredType + "] using property editor [" + editor + "]");
            }
            String newTextValue = (String) convertedValue;
            if (sharedEditor) {
                // Synchronized access to shared editor instance.
                synchronized (editor) {
                    return doConvertTextValue(oldValue, newTextValue, editor);
                }
            } else {
                // Unsynchronized access to non-shared editor instance.
                return doConvertTextValue(oldValue, newTextValue, editor);
            }
        } else if (String.class.equals(requiredType)) {
            returnValue = convertedValue;
        }
    }

    return returnValue;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String), for the specified property.
 * /*from w  w  w  .  ja  va2s .  com*/
 * @param propertyName
 *            name of the property
 * @param oldValue
 *            the previous value, if available (may be <code>null</code>)
 * @param newValue
 *            the proposed new value
 * @param requiredType
 *            the type we must convert to (or <code>null</code> if not known, for example in case of a collection
 *            element)
 * @param typeDescriptor
 *            the descriptor for the target property or field
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException
 *             if type conversion failed
 */
@SuppressWarnings("unchecked")
public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType,
        TypeDescriptor typeDescriptor) throws IllegalArgumentException {

    Object convertedValue = newValue;

    // Custom editor for this type?
    PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    ConversionFailedException firstAttemptEx = null;

    // No custom editor but custom ConversionService specified?
    ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
    if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) {
        TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
        TypeDescriptor targetTypeDesc = typeDescriptor;
        if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) {
            try {
                return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc);
            } catch (ConversionFailedException ex) {
                // fallback to default conversion logic below
                firstAttemptEx = ex;
            }
        }
    }

    // Value not of required type?
    if (editor != null
            || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
        if (requiredType != null && Collection.class.isAssignableFrom(requiredType)
                && convertedValue instanceof String) {
            TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor();
            if (elementType != null && Enum.class.isAssignableFrom(elementType.getType())) {
                convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
            }
        }
        if (editor == null) {
            editor = findDefaultEditor(requiredType);
        }
        convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    boolean standardConversion = false;

    if (requiredType != null) {
        // Try to apply some standard type conversion rules if appropriate.

        if (convertedValue != null) {
            if (requiredType.isArray()) {
                // Array required -> apply appropriate conversion of elements.
                if (convertedValue instanceof String
                        && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
                    convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                }
                return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
            } else if (convertedValue instanceof Collection) {
                // Convert elements to target type, if determined.
                convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName,
                        requiredType, typeDescriptor);
                standardConversion = true;
            } else if (convertedValue instanceof Map) {
                // Convert keys and values to respective target type, if determined.
                convertedValue = convertToTypedMap((Map) convertedValue, propertyName, requiredType,
                        typeDescriptor);
                standardConversion = true;
            }
            if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
                convertedValue = Array.get(convertedValue, 0);
                standardConversion = true;
            }
            if (String.class.equals(requiredType)
                    && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
                // We can stringify any primitive value...
                return (T) convertedValue.toString();
            } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
                if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
                    try {
                        Constructor strCtor = requiredType.getConstructor(String.class);
                        return (T) BeanUtils.instantiateClass(strCtor, convertedValue);
                    } catch (NoSuchMethodException ex) {
                        // proceed with field lookup
                        if (logger.isTraceEnabled()) {
                            logger.trace("No String constructor found on type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    } catch (Exception ex) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Construction via String failed for type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    }
                }
                String trimmedValue = ((String) convertedValue).trim();
                if (requiredType.isEnum() && "".equals(trimmedValue)) {
                    // It's an empty enum identifier: reset the enum value to null.
                    return null;
                }
                convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
                standardConversion = true;
            }
        }

        if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
            if (firstAttemptEx != null) {
                throw firstAttemptEx;
            }
            // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
            StringBuilder msg = new StringBuilder();
            msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
            msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]");
            if (propertyName != null) {
                msg.append(" for property '").append(propertyName).append("'");
            }
            if (editor != null) {
                msg.append(": PropertyEditor [").append(editor.getClass().getName())
                        .append("] returned inappropriate value of type [")
                        .append(ClassUtils.getDescriptiveType(convertedValue)).append("]");
                throw new IllegalArgumentException(msg.toString());
            } else {
                msg.append(": no matching editors or conversion strategy found");
                throw new IllegalStateException(msg.toString());
            }
        }
    }

    if (firstAttemptEx != null) {
        if (editor == null && !standardConversion && requiredType != null
                && !Object.class.equals(requiredType)) {
            throw firstAttemptEx;
        }
        logger.debug("Original ConversionService attempt failed - ignored since "
                + "PropertyEditor based conversion eventually succeeded", firstAttemptEx);
    }

    return (T) convertedValue;
}

From source file:com.springframework.beans.TypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String),
 * for the specified property.//from  w  ww .jav a  2 s. c  o  m
 * @param propertyName name of the property
 * @param oldValue the previous value, if available (may be {@code null})
 * @param newValue the proposed new value
 * @param requiredType the type we must convert to
 * (or {@code null} if not known, for example in case of a collection element)
 * @param typeDescriptor the descriptor for the target property or field
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException if type conversion failed
 */
@SuppressWarnings("unchecked")
public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType,
        TypeDescriptor typeDescriptor) throws IllegalArgumentException {

    Object convertedValue = newValue;

    // Custom editor for this type?
    PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    ConversionFailedException firstAttemptEx = null;

    // No custom editor but custom ConversionService specified?
    ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
    //      if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) {
    //         TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
    //         TypeDescriptor targetTypeDesc = typeDescriptor;
    //         if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) {
    //            try {
    //               return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc);
    //            }
    //            catch (ConversionFailedException ex) {
    //               // fallback to default conversion logic below
    //               firstAttemptEx = ex;
    //            }
    //         }
    //      }

    // Value not of required type?
    if (editor != null
            || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
        //         if (requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) {
        //            TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor();
        //            if (elementType != null && Enum.class.isAssignableFrom(elementType.getType())) {
        //               convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
        //            }
        //         }
        if (editor == null) {
            editor = findDefaultEditor(requiredType);
        }
        convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    boolean standardConversion = false;

    if (requiredType != null) {
        // Try to apply some standard type conversion rules if appropriate.

        if (convertedValue != null) {
            if (Object.class.equals(requiredType)) {
                return (T) convertedValue;
            }
            //            if (requiredType.isArray()) {
            //               // Array required -> apply appropriate conversion of elements.
            //               if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
            //                  convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
            //               }
            //               return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
            //            }
            //            else if (convertedValue instanceof Collection) {
            //               // Convert elements to target type, if determined.
            //               convertedValue = convertToTypedCollection(
            //                     (Collection<?>) convertedValue, propertyName, requiredType, typeDescriptor);
            //               standardConversion = true;
            //            }
            //            else if (convertedValue instanceof Map) {
            //               // Convert keys and values to respective target type, if determined.
            //               convertedValue = convertToTypedMap(
            //                     (Map<?, ?>) convertedValue, propertyName, requiredType, typeDescriptor);
            //               standardConversion = true;
            //            }
            //            if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
            //               convertedValue = Array.get(convertedValue, 0);
            //               standardConversion = true;
            //            }
            //            if (String.class.equals(requiredType) && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
            //               // We can stringify any primitive value...
            //               return (T) convertedValue.toString();
            //            }
            //            else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
            //               if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
            //                  try {
            //                     Constructor<T> strCtor = requiredType.getConstructor(String.class);
            //                     return BeanUtils.instantiateClass(strCtor, convertedValue);
            //                  }
            //                  catch (NoSuchMethodException ex) {
            //                     // proceed with field lookup
            //                     if (logger.isTraceEnabled()) {
            //                        logger.trace("No String constructor found on type [" + requiredType.getName() + "]", ex);
            //                     }
            //                  }
            //                  catch (Exception ex) {
            //                     if (logger.isDebugEnabled()) {
            //                        logger.debug("Construction via String failed for type [" + requiredType.getName() + "]", ex);
            //                     }
            //                  }
            //               }
            //               String trimmedValue = ((String) convertedValue).trim();
            //               if (requiredType.isEnum() && "".equals(trimmedValue)) {
            //                  // It's an empty enum identifier: reset the enum value to null.
            //                  return null;
            //               }
            //               convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
            //               standardConversion = true;
            //            }
            //         }
            //         else {
            //            // convertedValue == null
            //            if (javaUtilOptionalEmpty != null && requiredType.equals(javaUtilOptionalEmpty.getClass())) {
            //               convertedValue = javaUtilOptionalEmpty;
            //            }
        }

        if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
            if (firstAttemptEx != null) {
                throw firstAttemptEx;
            }
            // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
            StringBuilder msg = new StringBuilder();
            msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
            msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]");
            if (propertyName != null) {
                msg.append(" for property '").append(propertyName).append("'");
            }
            if (editor != null) {
                msg.append(": PropertyEditor [").append(editor.getClass().getName())
                        .append("] returned inappropriate value of type [")
                        .append(ClassUtils.getDescriptiveType(convertedValue)).append("]");
                throw new IllegalArgumentException(msg.toString());
            } else {
                msg.append(": no matching editors or conversion strategy found");
                throw new IllegalStateException(msg.toString());
            }
        }
    }

    if (firstAttemptEx != null) {
        if (editor == null && !standardConversion && requiredType != null
                && !Object.class.equals(requiredType)) {
            throw firstAttemptEx;
        }
        logger.debug("Original ConversionService attempt failed - ignored since "
                + "PropertyEditor based conversion eventually succeeded", firstAttemptEx);
    }

    return (T) convertedValue;
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

/**
 * Checks for structured properties. Structured properties are properties with a name
 * containg a "_".//from w  w  w . j  av  a2 s.  co m
 *
 * @param propertyValues
 */
private void checkStructuredProperties(MutablePropertyValues propertyValues) {
    Map<String, PropertyValue> valuesByName = new HashMap<String, PropertyValue>();
    List<String> valueNames = new ArrayList<String>();
    mapPropertyValues(propertyValues.getPropertyValues(), valuesByName, valueNames);

    while (!valueNames.isEmpty()) {
        String name = valueNames.remove(0);
        PropertyValue propertyValue = valuesByName.get(name);

        if (!isStructured(propertyValue)) {
            continue;
        }

        String propertyName = getNameOf(propertyValue);
        Class<?> type = bean.getPropertyType(propertyName);
        if (type == null) {
            continue;
        }

        PropertyEditor editor = findCustomEditor(type, propertyName);

        if (editor instanceof CompositeEditor) {
            CompositeEditor composite = (CompositeEditor) editor;
            List<PropertyEditor> propertyEditors = composite.getPropertyEditors();
            for (PropertyEditor propertyEditor : propertyEditors) {
                if (null == propertyEditor
                        || !StructuredPropertyEditor.class.isAssignableFrom(propertyEditor.getClass())) {
                    continue;
                }

                StructuredPropertyEditor structuredEditor = (StructuredPropertyEditor) propertyEditor;
                processStructuredProperty(structuredEditor, propertyName, type, valueNames, propertyValues);
            }
        } else {
            if (null == editor || !StructuredPropertyEditor.class.isAssignableFrom(editor.getClass())) {
                continue;
            }

            StructuredPropertyEditor structuredEditor = (StructuredPropertyEditor) editor;
            processStructuredProperty(structuredEditor, propertyName, type, valueNames, propertyValues);
        }
    }
}