Merged changes from trunk into branch (there were not many).
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/beanutils/branches/java5@1540184 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/pom.xml b/pom.xml
index d478769..4745077 100644
--- a/pom.xml
+++ b/pom.xml
@@ -308,6 +308,8 @@
- so we will just exclude it until someone comes up with a solution.
-->
<exclude>**/*MemoryTestCase.java</exclude>
+ <!-- Temporarily disabled long-running test case -->
+ <exclude>**/MemoryLeakTestCase.java</exclude>
</excludes>
<!-- Configure Logging -->
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index aa82a23..3165e00 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -40,6 +40,25 @@
<body>
<release version="1.9.0" date="tba" description="Upgrade to Java 5 including generics where possible">
+ <action dev="oheger" type="update" issue="BEANUTILS-452" >
+ Add generics
+ </action>
+ <action dev="oheger" type="update" issue="BEANUTILS-449" >
+ LocaleConverters do not take the target type into account
+ </action>
+ <action dev="oheger" type="update" issue="BEANUTILS-448" >
+ LocaleConverters do not check their default value
+ </action>
+ <action dev="oheger" type="update" issue="BEANUTILS-447" >
+ LazyDynaList.toArray() is not conform to the contract defined by the
+ Collection interface
+ </action>
+ <action dev="oheger" type="update" issue="BEANUTILS-446" >
+ Some of the converters ignore the passed in target type
+ </action>
+ <action dev="oheger" type="update" issue="BEANUTILS-445" >
+ Converters can return an invalid result object if a default value is set
+ </action>
<action dev="britter" type="update" issue="BEANUTILS-436" >
Replace package.html with package-info.java
</action>
diff --git a/src/main/java/org/apache/commons/beanutils/BaseDynaBeanMapDecorator.java b/src/main/java/org/apache/commons/beanutils/BaseDynaBeanMapDecorator.java
new file mode 100644
index 0000000..5d16894
--- /dev/null
+++ b/src/main/java/org/apache/commons/beanutils/BaseDynaBeanMapDecorator.java
@@ -0,0 +1,381 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.beanutils;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * <p>A base class for decorators providing <code>Map</code> behavior on
+ * {@link DynaBean}s.</p>
+ *
+ * <p>The motivation for this implementation is to provide access to {@link DynaBean}
+ * properties in technologies that are unaware of BeanUtils and {@link DynaBean}s -
+ * such as the expression languages of JSTL and JSF.</p>
+ *
+ * <p>This rather technical base class implements the methods of the
+ * {@code Map} interface on top of a {@code DynaBean}. It was introduced
+ * to handle generic parameters in a meaningful way without breaking
+ * backwards compatibility of the {@link DynaBeanMapDecorator} class: A
+ * map wrapping a {@code DynaBean} should be of type {@code Map<String, Object>}.
+ * However, when using these generic parameters in {@code DynaBeanMapDecorator}
+ * this would be an incompatible change (as method signatures would have to
+ * be adapted). To solve this problem, this generic base class is added
+ * which allows specifying the key type as parameter. This makes it easy to
+ * have a new subclass using the correct generic parameters while
+ * {@code DynaBeanMapDecorator} could still remain with compatible
+ * parameters.</p>
+ *
+ * @param <K> the type of the keys in the decorated map
+ * @since BeanUtils 1.9.0
+ * @version $Id$
+ */
+public abstract class BaseDynaBeanMapDecorator<K> implements Map<K, Object> {
+
+ private final DynaBean dynaBean;
+ private final boolean readOnly;
+ private transient Set<K> keySet;
+
+ // ------------------- Constructors ----------------------------------
+
+ /**
+ * Constructs a read only Map for the specified
+ * {@link DynaBean}.
+ *
+ * @param dynaBean The dyna bean being decorated
+ * @throws IllegalArgumentException if the {@link DynaBean} is null.
+ */
+ public BaseDynaBeanMapDecorator(DynaBean dynaBean) {
+ this(dynaBean, true);
+ }
+
+ /**
+ * Construct a Map for the specified {@link DynaBean}.
+ *
+ * @param dynaBean The dyna bean being decorated
+ * @param readOnly <code>true</code> if the Map is read only
+ * otherwise <code>false</code>
+ * @throws IllegalArgumentException if the {@link DynaBean} is null.
+ */
+ public BaseDynaBeanMapDecorator(DynaBean dynaBean, boolean readOnly) {
+ if (dynaBean == null) {
+ throw new IllegalArgumentException("DynaBean is null");
+ }
+ this.dynaBean = dynaBean;
+ this.readOnly = readOnly;
+ }
+
+
+ // ------------------- public Methods --------------------------------
+
+
+ /**
+ * Indicate whether the Map is read only.
+ *
+ * @return <code>true</code> if the Map is read only,
+ * otherwise <code>false</code>.
+ */
+ public boolean isReadOnly() {
+ return readOnly;
+ }
+
+ // ------------------- java.util.Map Methods -------------------------
+
+ /**
+ * clear() operation is not supported.
+ *
+ * @throws UnsupportedOperationException
+ */
+ public void clear() {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Indicate whether the {@link DynaBean} contains a specified
+ * value for one (or more) of its properties.
+ *
+ * @param key The {@link DynaBean}'s property name
+ * @return <code>true</code> if one of the {@link DynaBean}'s
+ * properties contains a specified value.
+ */
+ public boolean containsKey(Object key) {
+ DynaClass dynaClass = getDynaBean().getDynaClass();
+ DynaProperty dynaProperty = dynaClass.getDynaProperty(toString(key));
+ return (dynaProperty == null ? false : true);
+ }
+
+ /**
+ * Indicates whether the decorated {@link DynaBean} contains
+ * a specified value.
+ *
+ * @param value The value to check for.
+ * @return <code>true</code> if one of the the {@link DynaBean}'s
+ * properties contains the specified value, otherwise
+ * <code>false</code>.
+ */
+ public boolean containsValue(Object value) {
+ DynaProperty[] properties = getDynaProperties();
+ for (int i = 0; i < properties.length; i++) {
+ String key = properties[i].getName();
+ Object prop = getDynaBean().get(key);
+ if (value == null) {
+ if (prop == null) {
+ return true;
+ }
+ } else {
+ if (value.equals(prop)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * <p>Returns the Set of the property/value mappings
+ * in the decorated {@link DynaBean}.</p>
+ *
+ * <p>Each element in the Set is a <code>Map.Entry</code>
+ * type.</p>
+ *
+ * @return An unmodifiable set of the DynaBean
+ * property name/value pairs
+ */
+ public Set<Map.Entry<K, Object>> entrySet() {
+ DynaProperty[] properties = getDynaProperties();
+ Set<Map.Entry<K, Object>> set = new HashSet<Map.Entry<K, Object>>(properties.length);
+ for (int i = 0; i < properties.length; i++) {
+ K key = convertKey(properties[i].getName());
+ Object value = getDynaBean().get(properties[i].getName());
+ set.add(new MapEntry<K>(key, value));
+ }
+ return Collections.unmodifiableSet(set);
+ }
+
+ /**
+ * Return the value for the specified key from
+ * the decorated {@link DynaBean}.
+ *
+ * @param key The {@link DynaBean}'s property name
+ * @return The value for the specified property.
+ */
+ public Object get(Object key) {
+ return getDynaBean().get(toString(key));
+ }
+
+ /**
+ * Indicate whether the decorated {@link DynaBean} has
+ * any properties.
+ *
+ * @return <code>true</code> if the {@link DynaBean} has
+ * no properties, otherwise <code>false</code>.
+ */
+ public boolean isEmpty() {
+ return (getDynaProperties().length == 0);
+ }
+
+ /**
+ * <p>Returns the Set of the property
+ * names in the decorated {@link DynaBean}.</p>
+ *
+ * <p><b>N.B.</b>For {@link DynaBean}s whose associated {@link DynaClass}
+ * is a {@link MutableDynaClass} a new Set is created every
+ * time, otherwise the Set is created only once and cached.</p>
+ *
+ * @return An unmodifiable set of the {@link DynaBean}s
+ * property names.
+ */
+ public Set<K> keySet() {
+ if (keySet != null) {
+ return keySet;
+ }
+
+ // Create a Set of the keys
+ DynaProperty[] properties = getDynaProperties();
+ Set<K> set = new HashSet<K>(properties.length);
+ for (int i = 0; i < properties.length; i++) {
+ set.add(convertKey(properties[i].getName()));
+ }
+ set = Collections.unmodifiableSet(set);
+
+ // Cache the keySet if Not a MutableDynaClass
+ DynaClass dynaClass = getDynaBean().getDynaClass();
+ if (!(dynaClass instanceof MutableDynaClass)) {
+ keySet = set;
+ }
+
+ return set;
+
+ }
+
+ /**
+ * Set the value for the specified property in
+ * the decorated {@link DynaBean}.
+ *
+ * @param key The {@link DynaBean}'s property name
+ * @param value The value for the specified property.
+ * @return The previous property's value.
+ * @throws UnsupportedOperationException if
+ * <code>isReadOnly()</code> is true.
+ */
+ public Object put(K key, Object value) {
+ if (isReadOnly()) {
+ throw new UnsupportedOperationException("Map is read only");
+ }
+ String property = toString(key);
+ Object previous = getDynaBean().get(property);
+ getDynaBean().set(property, value);
+ return previous;
+ }
+
+ /**
+ * Copy the contents of a Map to the decorated {@link DynaBean}.
+ *
+ * @param map The Map of values to copy.
+ * @throws UnsupportedOperationException if
+ * <code>isReadOnly()</code> is true.
+ */
+ public void putAll(Map<? extends K, ? extends Object> map) {
+ if (isReadOnly()) {
+ throw new UnsupportedOperationException("Map is read only");
+ }
+ for (Map.Entry<? extends K, ?> e : map.entrySet()) {
+ put(e.getKey(), e.getValue());
+ }
+ }
+
+ /**
+ * remove() operation is not supported.
+ *
+ * @param key The {@link DynaBean}'s property name
+ * @return the value removed
+ * @throws UnsupportedOperationException
+ */
+ public Object remove(Object key) {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Returns the number properties in the decorated
+ * {@link DynaBean}.
+ * @return The number of properties.
+ */
+ public int size() {
+ return getDynaProperties().length;
+ }
+
+ /**
+ * Returns the set of property values in the
+ * decorated {@link DynaBean}.
+ *
+ * @return Unmodifiable collection of values.
+ */
+ public Collection<Object> values() {
+ DynaProperty[] properties = getDynaProperties();
+ List<Object> values = new ArrayList<Object>(properties.length);
+ for (int i = 0; i < properties.length; i++) {
+ String key = properties[i].getName();
+ Object value = getDynaBean().get(key);
+ values.add(value);
+ }
+ return Collections.unmodifiableList(values);
+ }
+
+ // ------------------- protected Methods -----------------------------
+
+ /**
+ * Provide access to the underlying {@link DynaBean}
+ * this Map decorates.
+ *
+ * @return the decorated {@link DynaBean}.
+ */
+ public DynaBean getDynaBean() {
+ return dynaBean;
+ }
+
+ /**
+ * Converts the name of a property to the key type of this decorator.
+ *
+ * @param propertyName the name of a property
+ * @return the converted key to be used in the decorated map
+ */
+ protected abstract K convertKey(String propertyName);
+
+ // ------------------- private Methods -------------------------------
+
+ /**
+ * Convenience method to retrieve the {@link DynaProperty}s
+ * for this {@link DynaClass}.
+ *
+ * @return The an array of the {@link DynaProperty}s.
+ */
+ private DynaProperty[] getDynaProperties() {
+ return getDynaBean().getDynaClass().getDynaProperties();
+ }
+
+ /**
+ * Convenience method to convert an Object
+ * to a String.
+ *
+ * @param obj The Object to convert
+ * @return String representation of the object
+ */
+ private String toString(Object obj) {
+ return (obj == null ? null : obj.toString());
+ }
+
+ /**
+ * Map.Entry implementation.
+ */
+ private static class MapEntry<K> implements Map.Entry<K, Object> {
+ private final K key;
+ private final Object value;
+ MapEntry(K key, Object value) {
+ this.key = key;
+ this.value = value;
+ }
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof Map.Entry)) {
+ return false;
+ }
+ Map.Entry<?, ?> e = (Map.Entry<?, ?>)o;
+ return ((key.equals(e.getKey())) &&
+ (value == null ? e.getValue() == null
+ : value.equals(e.getValue())));
+ }
+ @Override
+ public int hashCode() {
+ return key.hashCode() + (value == null ? 0 : value.hashCode());
+ }
+ public K getKey() {
+ return key;
+ }
+ public Object getValue() {
+ return value;
+ }
+ public Object setValue(Object value) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+}
diff --git a/src/main/java/org/apache/commons/beanutils/BasicDynaBean.java b/src/main/java/org/apache/commons/beanutils/BasicDynaBean.java
index de2be2f..3f62115 100644
--- a/src/main/java/org/apache/commons/beanutils/BasicDynaBean.java
+++ b/src/main/java/org/apache/commons/beanutils/BasicDynaBean.java
@@ -73,10 +73,10 @@
/**
* The set of property values for this DynaBean, keyed by property name.
*/
- protected HashMap values = new HashMap();
+ protected HashMap<String, Object> values = new HashMap<String, Object>();
/** Map decorator for this DynaBean */
- private transient Map mapDecorator;
+ private transient Map<String, Object> mapDecorator;
/**
* Return a Map representation of this DynaBean.
@@ -88,11 +88,11 @@
* @return a Map representation of this DynaBean
* @since 1.8.0
*/
- public Map getMap() {
+ public Map<String, Object> getMap() {
// cache the Map
if (mapDecorator == null) {
- mapDecorator = new DynaBeanMapDecorator(this);
+ mapDecorator = new DynaBeanPropertyMapDecorator(this);
}
return mapDecorator;
@@ -120,7 +120,7 @@
throw new NullPointerException
("No mapped value for '" + name + "(" + key + ")'");
} else if (value instanceof Map) {
- return (((Map) value).containsKey(key));
+ return (((Map<?, ?>) value).containsKey(key));
} else {
throw new IllegalArgumentException
("Non-mapped property for '" + name + "(" + key + ")'");
@@ -147,7 +147,7 @@
}
// Return a null value for a non-primitive property
- Class type = getDynaProperty(name).getType();
+ Class<?> type = getDynaProperty(name).getType();
if (!type.isPrimitive()) {
return (value);
}
@@ -201,7 +201,7 @@
} else if (value.getClass().isArray()) {
return (Array.get(value, index));
} else if (value instanceof List) {
- return ((List) value).get(index);
+ return ((List<?>) value).get(index);
} else {
throw new IllegalArgumentException
("Non-indexed property for '" + name + "[" + index + "]'");
@@ -230,7 +230,7 @@
throw new NullPointerException
("No mapped value for '" + name + "(" + key + ")'");
} else if (value instanceof Map) {
- return (((Map) value).get(key));
+ return (((Map<?, ?>) value).get(key));
} else {
throw new IllegalArgumentException
("Non-mapped property for '" + name + "(" + key + ")'");
@@ -270,7 +270,7 @@
throw new NullPointerException
("No mapped value for '" + name + "(" + key + ")'");
} else if (value instanceof Map) {
- ((Map) value).remove(key);
+ ((Map<?, ?>) value).remove(key);
} else {
throw new IllegalArgumentException
("Non-mapped property for '" + name + "(" + key + ")'");
@@ -338,7 +338,11 @@
Array.set(prop, index, value);
} else if (prop instanceof List) {
try {
- ((List) prop).set(index, value);
+ @SuppressWarnings("unchecked")
+ // This is safe to cast because list properties are always
+ // of type Object
+ List<Object> list = (List<Object>) prop;
+ list.set(index, value);
} catch (ClassCastException e) {
throw new ConversionException(e.getMessage());
}
@@ -371,7 +375,11 @@
throw new NullPointerException
("No mapped value for '" + name + "(" + key + ")'");
} else if (prop instanceof Map) {
- ((Map) prop).put(key, value);
+ @SuppressWarnings("unchecked")
+ // This is safe to cast because mapped properties are always
+ // maps of types String -> Object
+ Map<String, Object> map = (Map<String, Object>) prop;
+ map.put(key, value);
} else {
throw new IllegalArgumentException
("Non-mapped property for '" + name + "(" + key + ")'");
@@ -412,7 +420,7 @@
* @return <code>true</code> if the source class is assignable to the
* destination class, otherwise <code>false</code>
*/
- protected boolean isAssignable(Class dest, Class source) {
+ protected boolean isAssignable(Class<?> dest, Class<?> source) {
if (dest.isAssignableFrom(source) ||
((dest == Boolean.TYPE) && (source == Boolean.class)) ||
diff --git a/src/main/java/org/apache/commons/beanutils/BasicDynaClass.java b/src/main/java/org/apache/commons/beanutils/BasicDynaClass.java
index 2ef3680..284c4f2 100644
--- a/src/main/java/org/apache/commons/beanutils/BasicDynaClass.java
+++ b/src/main/java/org/apache/commons/beanutils/BasicDynaClass.java
@@ -58,7 +58,7 @@
* @param name Name of this DynaBean class
* @param dynaBeanClass The implementation class for new instances
*/
- public BasicDynaClass(String name, Class dynaBeanClass) {
+ public BasicDynaClass(String name, Class<?> dynaBeanClass) {
this(name, dynaBeanClass, null);
@@ -72,7 +72,7 @@
* @param dynaBeanClass The implementation class for new intances
* @param properties Property descriptors for the supported properties
*/
- public BasicDynaClass(String name, Class dynaBeanClass,
+ public BasicDynaClass(String name, Class<?> dynaBeanClass,
DynaProperty[] properties) {
super();
@@ -97,14 +97,14 @@
* The constructor of the <code>dynaBeanClass</code> that we will use
* for creating new instances.
*/
- protected transient Constructor constructor = null;
+ protected transient Constructor<?> constructor = null;
/**
* The method signature of the constructor we will use to create
* new DynaBean instances.
*/
- protected static Class[] constructorTypes = { DynaClass.class };
+ protected static Class<?>[] constructorTypes = { DynaClass.class };
/**
@@ -118,7 +118,7 @@
* The <code>DynaBean</code> implementation class we will use for
* creating new instances.
*/
- protected Class dynaBeanClass = BasicDynaBean.class;
+ protected Class<?> dynaBeanClass = BasicDynaBean.class;
/**
@@ -138,7 +138,7 @@
* keyed by the property name. Individual descriptor instances will
* be the same instances as those in the <code>properties</code> list.
*/
- protected HashMap propertiesMap = new HashMap();
+ protected HashMap<String, DynaProperty> propertiesMap = new HashMap<String, DynaProperty>();
// ------------------------------------------------------ DynaClass Methods
@@ -175,7 +175,7 @@
throw new IllegalArgumentException
("No property name specified");
}
- return ((DynaProperty) propertiesMap.get(name));
+ return propertiesMap.get(name);
}
@@ -237,7 +237,7 @@
*
* @return The class of the {@link DynaBean}
*/
- public Class getDynaBeanClass() {
+ public Class<?> getDynaBeanClass() {
return (this.dynaBeanClass);
@@ -257,7 +257,7 @@
* @exception IllegalArgumentException if the specified Class does not
* implement the <code>DynaBean</code> interface
*/
- protected void setDynaBeanClass(Class dynaBeanClass) {
+ protected void setDynaBeanClass(Class<?> dynaBeanClass) {
// Validate the argument type specified
if (dynaBeanClass.isInterface()) {
diff --git a/src/main/java/org/apache/commons/beanutils/BeanComparator.java b/src/main/java/org/apache/commons/beanutils/BeanComparator.java
index 0c8f954..59a12d9 100644
--- a/src/main/java/org/apache/commons/beanutils/BeanComparator.java
+++ b/src/main/java/org/apache/commons/beanutils/BeanComparator.java
@@ -17,9 +17,10 @@
package org.apache.commons.beanutils;
-import java.lang.reflect.InvocationTargetException;
import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
import java.util.Comparator;
+
import org.apache.commons.collections.comparators.ComparableComparator;
/**
@@ -35,14 +36,20 @@
* specified in the constructor. If you are comparing two beans based
* on a property that could contain "null" values, a suitable <code>Comparator</code>
* or <code>ComparatorChain</code> should be supplied in the constructor.
+ * Note that the passed in {@code Comparator} must be able to handle the
+ * passed in objects. Because the type of the property to be compared is not
+ * known at compile time no type checks can be performed by the compiler.
+ * Thus {@code ClassCastException} exceptions can be thrown if unexpected
+ * property values occur.
* </p>
*
+ * @param <B> the type of beans to be compared by this {@code Comparator}
* @version $Id$
*/
-public class BeanComparator implements Comparator, Serializable {
+public class BeanComparator<B> implements Comparator<B>, Serializable {
private String property;
- private Comparator comparator;
+ private final Comparator<?> comparator;
/**
* <p>Constructs a Bean Comparator without a property set.
@@ -96,7 +103,7 @@
* contains null values, a suitable comparator
* may be supplied in this constructor.
*/
- public BeanComparator( String property, Comparator comparator ) {
+ public BeanComparator( String property, Comparator<?> comparator ) {
setProperty( property );
if (comparator != null) {
this.comparator = comparator;
@@ -132,7 +139,7 @@
*
* @return the Comparator being used to compare beans
*/
- public Comparator getComparator() {
+ public Comparator<?> getComparator() {
return comparator;
}
@@ -145,17 +152,17 @@
* @param o2 Object The second bean to get data from to compare
* @return int negative or positive based on order
*/
- public int compare( Object o1, Object o2 ) {
+ public int compare( B o1, B o2 ) {
if ( property == null ) {
// compare the actual objects
- return comparator.compare( o1, o2 );
+ return internalCompare( o1, o2 );
}
try {
Object value1 = PropertyUtils.getProperty( o1, property );
Object value2 = PropertyUtils.getProperty( o2, property );
- return comparator.compare( value1, value2 );
+ return internalCompare( value1, value2 );
}
catch ( IllegalAccessException iae ) {
throw new RuntimeException( "IllegalAccessException: " + iae.toString() );
@@ -184,7 +191,7 @@
return false;
}
- final BeanComparator beanComparator = (BeanComparator) o;
+ final BeanComparator<?> beanComparator = (BeanComparator<?>) o;
if (!comparator.equals(beanComparator.comparator)) {
return false;
@@ -213,4 +220,20 @@
result = comparator.hashCode();
return result;
}
+
+ /**
+ * Compares the given values using the internal {@code Comparator}.
+ * <em>Note</em>: This comparison cannot be performed in a type-safe way; so
+ * {@code ClassCastException} exceptions may be thrown.
+ *
+ * @param val1 the first value to be compared
+ * @param val2 the second value to be compared
+ * @return the result of the comparison
+ */
+ private int internalCompare(Object val1, Object val2) {
+ @SuppressWarnings("rawtypes")
+ // to make the compiler happy
+ Comparator c = comparator;
+ return c.compare(val1, val2);
+ }
}
diff --git a/src/main/java/org/apache/commons/beanutils/BeanMap.java b/src/main/java/org/apache/commons/beanutils/BeanMap.java
index a8c1f13..2692bc3 100644
--- a/src/main/java/org/apache/commons/beanutils/BeanMap.java
+++ b/src/main/java/org/apache/commons/beanutils/BeanMap.java
@@ -33,10 +33,9 @@
import java.util.Map;
import java.util.Set;
-import org.apache.commons.collections.list.UnmodifiableList;
+import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.keyvalue.AbstractMapEntry;
import org.apache.commons.collections.set.UnmodifiableSet;
-import org.apache.commons.collections.Transformer;
/**
* An implementation of Map for JavaBeans which uses introspection to
@@ -47,7 +46,7 @@
*
* @version $Id$
*/
-public class BeanMap extends AbstractMap implements Cloneable {
+public class BeanMap extends AbstractMap<Object, Object> implements Cloneable {
private transient Object bean;
@@ -499,8 +498,11 @@
* @return BeanMap keys. The Set returned by this method is not
* modifiable.
*/
+ @SuppressWarnings("unchecked")
+ // The set actually contains strings; however, because it cannot be
+ // modified there is no danger in selling it as Set<Object>
@Override
- public Set keySet() {
+ public Set<Object> keySet() {
return UnmodifiableSet.decorate(readMethods.keySet());
}
@@ -512,10 +514,10 @@
* @return the unmodifiable set of mappings
*/
@Override
- public Set entrySet() {
- return UnmodifiableSet.decorate(new AbstractSet() {
+ public Set<Map.Entry<Object, Object>> entrySet() {
+ return Collections.unmodifiableSet(new AbstractSet<Map.Entry<Object, Object>>() {
@Override
- public Iterator iterator() {
+ public Iterator<Map.Entry<Object, Object>> iterator() {
return entryIterator();
}
@Override
@@ -532,12 +534,12 @@
* modifiable.
*/
@Override
- public Collection values() {
- ArrayList answer = new ArrayList( readMethods.size() );
- for ( Iterator iter = valueIterator(); iter.hasNext(); ) {
+ public Collection<Object> values() {
+ ArrayList<Object> answer = new ArrayList<Object>( readMethods.size() );
+ for ( Iterator<Object> iter = valueIterator(); iter.hasNext(); ) {
answer.add( iter.next() );
}
- return UnmodifiableList.decorate(answer);
+ return Collections.unmodifiableList(answer);
}
@@ -551,7 +553,7 @@
* @return the type of the property, or <code>null</code> if no such
* property exists
*/
- public Class getType(String name) {
+ public Class<?> getType(String name) {
return types.get( name );
}
@@ -562,7 +564,7 @@
*
* @return an iterator over the keys
*/
- public Iterator keyIterator() {
+ public Iterator<String> keyIterator() {
return readMethods.keySet().iterator();
}
@@ -571,9 +573,9 @@
*
* @return an iterator over the values
*/
- public Iterator valueIterator() {
- final Iterator iter = keyIterator();
- return new Iterator() {
+ public Iterator<Object> valueIterator() {
+ final Iterator<?> iter = keyIterator();
+ return new Iterator<Object>() {
public boolean hasNext() {
return iter.hasNext();
}
@@ -592,16 +594,20 @@
*
* @return an iterator over the entries
*/
- public Iterator entryIterator() {
- final Iterator iter = keyIterator();
- return new Iterator() {
+ public Iterator<Map.Entry<Object, Object>> entryIterator() {
+ final Iterator<String> iter = keyIterator();
+ return new Iterator<Map.Entry<Object, Object>>() {
public boolean hasNext() {
return iter.hasNext();
}
- public Object next() {
+ public Map.Entry<Object, Object> next() {
Object key = iter.next();
Object value = get(key);
- return new Entry( BeanMap.this, key, value );
+ @SuppressWarnings("unchecked")
+ // This should not cause any problems; the key is actually a
+ // string, but it does no harm to expose it as Object
+ Map.Entry<Object, Object> tmpEntry = new Entry( BeanMap.this, key, value );
+ return tmpEntry;
}
public void remove() {
throw new UnsupportedOperationException( "remove() not supported for BeanMap" );
@@ -857,7 +863,7 @@
* @throws IllegalAccessException never
* @throws IllegalArgumentException never
*/
- protected Object convertType( Class newType, Object value )
+ protected Object convertType( Class<?> newType, Object value )
throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// try call constructor
@@ -884,7 +890,7 @@
* @return a transformer that will convert strings into that type,
* or null if the given type is not a primitive type
*/
- protected Transformer getTypeTransformer( Class aType ) {
+ protected Transformer getTypeTransformer( Class<?> aType ) {
return typeTransformers.get( aType );
}
diff --git a/src/main/java/org/apache/commons/beanutils/BeanUtils.java b/src/main/java/org/apache/commons/beanutils/BeanUtils.java
index 7172e47..5ef8ac3 100644
--- a/src/main/java/org/apache/commons/beanutils/BeanUtils.java
+++ b/src/main/java/org/apache/commons/beanutils/BeanUtils.java
@@ -176,7 +176,7 @@
* property cannot be found
* @see BeanUtilsBean#describe
*/
- public static Map describe(Object bean)
+ public static Map<String, String> describe(Object bean)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
@@ -425,7 +425,7 @@
* throws an exception
* @see BeanUtilsBean#populate
*/
- public static void populate(Object bean, Map properties)
+ public static void populate(Object bean, Map<String, ? extends Object> properties)
throws IllegalAccessException, InvocationTargetException {
BeanUtilsBean.getInstance().populate(bean, properties);
@@ -468,11 +468,13 @@
/**
* Create a cache.
+ * @param <K> the key type of the cache
+ * @param <V> the value type of the cache
* @return a new cache
* @since 1.8.0
*/
- public static Map createCache() {
- return new WeakFastHashMap();
+ public static <K, V> Map<K, V> createCache() {
+ return new WeakFastHashMap<K, V>();
}
/**
@@ -481,9 +483,9 @@
* @return Whether it is fast or not.
* @since 1.8.0
*/
- public static boolean getCacheFast(Map map) {
+ public static boolean getCacheFast(Map<?, ?> map) {
if (map instanceof WeakFastHashMap) {
- return ((WeakFastHashMap)map).getFast();
+ return ((WeakFastHashMap<?, ?>) map).getFast();
} else {
return false;
}
@@ -495,9 +497,9 @@
* @param fast Whether it should be fast or not.
* @since 1.8.0
*/
- public static void setCacheFast(Map map, boolean fast) {
+ public static void setCacheFast(Map<?, ?> map, boolean fast) {
if (map instanceof WeakFastHashMap) {
- ((WeakFastHashMap)map).setFast(fast);
+ ((WeakFastHashMap<?, ?>)map).setFast(fast);
}
}
}
diff --git a/src/main/java/org/apache/commons/beanutils/BeanUtilsBean.java b/src/main/java/org/apache/commons/beanutils/BeanUtilsBean.java
index 2569875..37df709 100644
--- a/src/main/java/org/apache/commons/beanutils/BeanUtilsBean.java
+++ b/src/main/java/org/apache/commons/beanutils/BeanUtilsBean.java
@@ -27,7 +27,6 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import org.apache.commons.beanutils.expression.Resolver;
@@ -56,11 +55,11 @@
/**
* Contains <code>BeanUtilsBean</code> instances indexed by context classloader.
*/
- private static final ContextClassLoaderLocal
- BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal() {
+ private static final ContextClassLoaderLocal<BeanUtilsBean>
+ BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal<BeanUtilsBean>() {
// Creates the default instance used when the context classloader is unavailable
@Override
- protected Object initialValue() {
+ protected BeanUtilsBean initialValue() {
return new BeanUtilsBean();
}
};
@@ -73,7 +72,7 @@
* @return The (pseudo-singleton) BeanUtils bean instance
*/
public static BeanUtilsBean getInstance() {
- return (BeanUtilsBean) BEANS_BY_CLASSLOADER.get();
+ return BEANS_BY_CLASSLOADER.get();
}
/**
@@ -258,10 +257,11 @@
}
}
} else if (orig instanceof Map) {
- Iterator entries = ((Map) orig).entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
- String name = (String)entry.getKey();
+ @SuppressWarnings("unchecked")
+ // Map properties are always of type <String, Object>
+ Map<String, Object> propMap = (Map<String, Object>) orig;
+ for (Map.Entry<String, Object> entry : propMap.entrySet()) {
+ String name = entry.getKey();
if (getPropertyUtils().isWriteable(dest, name)) {
copyProperty(dest, name, entry.getValue());
}
@@ -370,7 +370,7 @@
// Declare local variables we will require
String propName = resolver.getProperty(name); // Simple name of target property
- Class type = null; // Java type of target property
+ Class<?> type = null; // Java type of target property
int index = resolver.getIndex(name); // Indexed subscript value (if any)
String key = resolver.getKey(name); // Mapped key value (if any)
@@ -381,7 +381,7 @@
if (dynaProperty == null) {
return; // Skip this property setter
}
- type = dynaProperty.getType();
+ type = dynaPropertyType(dynaProperty, value);
} else {
PropertyDescriptor descriptor = null;
try {
@@ -479,20 +479,20 @@
* @exception NoSuchMethodException if an accessor method for this
* property cannot be found
*/
- public Map describe(Object bean)
+ public Map<String, String> describe(Object bean)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
if (bean == null) {
// return (Collections.EMPTY_MAP);
- return (new java.util.HashMap());
+ return (new java.util.HashMap<String, String>());
}
if (log.isDebugEnabled()) {
log.debug("Describing bean: " + bean.getClass().getName());
}
- Map description = new HashMap();
+ Map<String, String> description = new HashMap<String, String>();
if (bean instanceof DynaBean) {
DynaProperty[] descriptors =
((DynaBean) bean).getDynaClass().getDynaProperties();
@@ -503,7 +503,7 @@
} else {
PropertyDescriptor[] descriptors =
getPropertyUtils().getPropertyDescriptors(bean);
- Class clazz = bean.getClass();
+ Class<?> clazz = bean.getClass();
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
if (getPropertyUtils().getReadMethod(clazz, descriptors[i]) != null) {
@@ -539,18 +539,16 @@
if (value == null) {
return (null);
} else if (value instanceof Collection) {
- ArrayList values = new ArrayList();
- Iterator items = ((Collection) value).iterator();
- while (items.hasNext()) {
- Object item = items.next();
+ ArrayList<String> values = new ArrayList<String>();
+ for (Object item : (Collection<?>) value) {
if (item == null) {
- values.add((String) null);
+ values.add(null);
} else {
// convert to string using convert utils
values.add(getConvertUtils().convert(item));
}
}
- return ((String[]) values.toArray(new String[values.size()]));
+ return (values.toArray(new String[values.size()]));
} else if (value.getClass().isArray()) {
int n = Array.getLength(value);
String[] results = new String[n];
@@ -799,7 +797,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
*/
- public void populate(Object bean, Map properties)
+ public void populate(Object bean, Map<String, ? extends Object> properties)
throws IllegalAccessException, InvocationTargetException {
// Do nothing unless both arguments have been specified
@@ -812,12 +810,9 @@
}
// Loop through the property name/value pairs to be set
- Iterator entries = properties.entrySet().iterator();
- while (entries.hasNext()) {
-
+ for(Map.Entry<String, ? extends Object> entry : properties.entrySet()) {
// Identify the property name and value(s) to be assigned
- Map.Entry entry = (Map.Entry)entries.next();
- String name = (String) entry.getKey();
+ String name = entry.getKey();
if (name == null) {
continue;
}
@@ -912,7 +907,7 @@
// Declare local variables we will require
String propName = resolver.getProperty(name); // Simple name of target property
- Class type = null; // Java type of target property
+ Class<?> type = null; // Java type of target property
int index = resolver.getIndex(name); // Indexed subscript value (if any)
String key = resolver.getKey(name); // Mapped key value (if any)
@@ -923,7 +918,7 @@
if (dynaProperty == null) {
return; // Skip this property setter
}
- type = dynaProperty.getType();
+ type = dynaPropertyType(dynaProperty, value);
} else if (target instanceof Map) {
type = Object.class;
} else if (target != null && target.getClass().isArray() && index >= 0) {
@@ -1070,7 +1065,7 @@
* @exception ConversionException if thrown by an underlying Converter
* @since 1.8.0
*/
- protected Object convert(Object value, Class type) {
+ protected Object convert(Object value, Class<?> type) {
Converter converter = getConvertUtils().lookup(type);
if (converter != null) {
log.trace(" USING CONVERTER " + converter);
@@ -1091,7 +1086,7 @@
*/
private static Method getInitCauseMethod() {
try {
- Class[] paramsClasses = new Class[] { Throwable.class };
+ Class<?>[] paramsClasses = new Class<?>[] { Throwable.class };
return Throwable.class.getMethod("initCause", paramsClasses);
} catch (NoSuchMethodException e) {
Log log = LogFactory.getLog(BeanUtils.class);
@@ -1107,4 +1102,20 @@
return null;
}
}
+
+ /**
+ * Determines the type of a {@code DynaProperty}. Here a special treatment
+ * is needed for mapped properties.
+ *
+ * @param dynaProperty the property descriptor
+ * @param value the value object to be set for this property
+ * @return the type of this property
+ */
+ private static Class<?> dynaPropertyType(DynaProperty dynaProperty,
+ Object value) {
+ if (!dynaProperty.isMapped()) {
+ return dynaProperty.getType();
+ }
+ return (value == null) ? String.class : value.getClass();
+ }
}
diff --git a/src/main/java/org/apache/commons/beanutils/BeanUtilsBean2.java b/src/main/java/org/apache/commons/beanutils/BeanUtilsBean2.java
index ee88188..1abaa71 100644
--- a/src/main/java/org/apache/commons/beanutils/BeanUtilsBean2.java
+++ b/src/main/java/org/apache/commons/beanutils/BeanUtilsBean2.java
@@ -70,7 +70,7 @@
* @return The converted value
*/
@Override
- protected Object convert(Object value, Class type) {
+ protected Object convert(Object value, Class<?> type) {
return getConvertUtils().convert(value, type);
}
}
diff --git a/src/main/java/org/apache/commons/beanutils/ConstructorUtils.java b/src/main/java/org/apache/commons/beanutils/ConstructorUtils.java
index e58808d..0373974 100644
--- a/src/main/java/org/apache/commons/beanutils/ConstructorUtils.java
+++ b/src/main/java/org/apache/commons/beanutils/ConstructorUtils.java
@@ -42,7 +42,7 @@
// --------------------------------------------------------- Private Members
/** An empty class array */
- private static final Class[] EMPTY_CLASS_PARAMETERS = new Class[0];
+ private static final Class<?>[] EMPTY_CLASS_PARAMETERS = new Class<?>[0];
/** An empty object array */
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
@@ -55,6 +55,7 @@
*
* <p>The signatures should be assignment compatible.</p>
*
+ * @param <T> the type of the object to be constructed
* @param klass the class to be constructed.
* @param arg the actual argument. May be null (this will result in calling the default constructor).
* @return new instance of <code>klazz</code>
@@ -66,7 +67,7 @@
*
* @see #invokeConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
*/
- public static Object invokeConstructor(Class klass, Object arg)
+ public static <T> T invokeConstructor(Class<T> klass, Object arg)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -84,6 +85,7 @@
*
* <p>The signatures should be assignment compatible.</p>
*
+ * @param <T> the type of the object to be constructed
* @param klass the class to be constructed.
* @param args actual argument array. May be null (this will result in calling the default constructor).
* @return new instance of <code>klazz</code>
@@ -95,7 +97,7 @@
*
* @see #invokeConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
*/
- public static Object invokeConstructor(Class klass, Object[] args)
+ public static <T> T invokeConstructor(Class<T> klass, Object[] args)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -106,7 +108,7 @@
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
- Class parameterTypes[] = new Class[arguments];
+ Class<?> parameterTypes[] = new Class<?>[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
@@ -119,6 +121,7 @@
*
* <p>The signatures should be assignment compatible.</p>
*
+ * @param <T> the type of the object to be constructed
* @param klass the class to be constructed.
* @param args actual argument array. May be null (this will result in calling the default constructor).
* @param parameterTypes parameter types array
@@ -130,10 +133,10 @@
* @throws InstantiationException thrown on the constructor's invocation
* @see Constructor#newInstance
*/
- public static Object invokeConstructor(
- Class klass,
+ public static <T> T invokeConstructor(
+ Class<T> klass,
Object[] args,
- Class[] parameterTypes)
+ Class<?>[] parameterTypes)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -147,7 +150,7 @@
args = EMPTY_OBJECT_ARRAY;
}
- Constructor ctor =
+ Constructor<T> ctor =
getMatchingAccessibleConstructor(klass, parameterTypes);
if (null == ctor) {
throw new NoSuchMethodException(
@@ -164,6 +167,7 @@
*
* <p>The signatures should match exactly.</p>
*
+ * @param <T> the type of the object to be constructed
* @param klass the class to be constructed.
* @param arg the actual argument. May be null (this will result in calling the default constructor).
* @return new instance of <code>klazz</code>
@@ -175,7 +179,7 @@
*
* @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
*/
- public static Object invokeExactConstructor(Class klass, Object arg)
+ public static <T> T invokeExactConstructor(Class<T> klass, Object arg)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -193,6 +197,7 @@
*
* <p>The signatures should match exactly.</p>
*
+ * @param <T> the type of the object to be constructed
* @param klass the class to be constructed.
* @param args actual argument array. May be null (this will result in calling the default constructor).
* @return new instance of <code>klazz</code>
@@ -204,7 +209,7 @@
*
* @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
*/
- public static Object invokeExactConstructor(Class klass, Object[] args)
+ public static <T> T invokeExactConstructor(Class<T> klass, Object[] args)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -215,7 +220,7 @@
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
- Class parameterTypes[] = new Class[arguments];
+ Class<?> parameterTypes[] = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
@@ -229,6 +234,7 @@
*
* <p>The signatures should match exactly.</p>
*
+ * @param <T> the type of the object to be constructed
* @param klass the class to be constructed.
* @param args actual argument array. May be null (this will result in calling the default constructor).
* @param parameterTypes parameter types array
@@ -240,10 +246,10 @@
* @throws InstantiationException thrown on the constructor's invocation
* @see Constructor#newInstance
*/
- public static Object invokeExactConstructor(
- Class klass,
+ public static <T> T invokeExactConstructor(
+ Class<T> klass,
Object[] args,
- Class[] parameterTypes)
+ Class<?>[] parameterTypes)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -258,7 +264,7 @@
parameterTypes = EMPTY_CLASS_PARAMETERS;
}
- Constructor ctor = getAccessibleConstructor(klass, parameterTypes);
+ Constructor<T> ctor = getAccessibleConstructor(klass, parameterTypes);
if (null == ctor) {
throw new NoSuchMethodException(
"No such accessible constructor on object: " + klass.getName());
@@ -268,17 +274,18 @@
/**
* Returns a constructor with single argument.
+ * @param <T> the type of the constructor
* @param klass the class to be constructed
* @param parameterType The constructor parameter type
* @return null if matching accessible constructor can not be found.
* @see Class#getConstructor
* @see #getAccessibleConstructor(java.lang.reflect.Constructor)
*/
- public static Constructor getAccessibleConstructor(
- Class klass,
- Class parameterType) {
+ public static <T> Constructor<T> getAccessibleConstructor(
+ Class<T> klass,
+ Class<?> parameterType) {
- Class[] parameterTypes = { parameterType };
+ Class<?>[] parameterTypes = { parameterType };
return getAccessibleConstructor(klass, parameterTypes);
}
@@ -290,9 +297,9 @@
* @see Class#getConstructor
* @see #getAccessibleConstructor(java.lang.reflect.Constructor)
*/
- public static Constructor getAccessibleConstructor(
- Class klass,
- Class[] parameterTypes) {
+ public static <T> Constructor<T> getAccessibleConstructor(
+ Class<T> klass,
+ Class<?>[] parameterTypes) {
try {
return getAccessibleConstructor(
@@ -304,11 +311,12 @@
/**
* Returns accessible version of the given constructor.
+ * @param <T> the type of the constructor
* @param ctor prototype constructor object.
* @return <code>null</code> if accessible constructor can not be found.
* @see java.lang.SecurityManager
*/
- public static Constructor getAccessibleConstructor(Constructor ctor) {
+ public static <T> Constructor<T> getAccessibleConstructor(Constructor<T> ctor) {
// Make sure we have a method to check
if (ctor == null) {
@@ -321,7 +329,7 @@
}
// If the declaring class is public, we are done
- Class clazz = ctor.getDeclaringClass();
+ Class<T> clazz = ctor.getDeclaringClass();
if (Modifier.isPublic(clazz.getModifiers())) {
return (ctor);
}
@@ -350,17 +358,18 @@
* are assignment compatible with the parameter types.
* The first matching constructor is returned.</p>
*
+ * @param <T> the type of the class to be inspected
* @param clazz find constructor for this class
* @param parameterTypes find method with compatible parameters
* @return a valid Constructor object. If there's no matching constructor, returns <code>null</code>.
*/
- private static Constructor getMatchingAccessibleConstructor(
- Class clazz,
- Class[] parameterTypes) {
+ private static <T> Constructor<T> getMatchingAccessibleConstructor(
+ Class<T> clazz,
+ Class<?>[] parameterTypes) {
// see if we can find the method directly
// most of the time this works and it's much faster
try {
- Constructor ctor = clazz.getConstructor(parameterTypes);
+ Constructor<T> ctor = clazz.getConstructor(parameterTypes);
try {
//
// XXX Default access superclass workaround
@@ -389,10 +398,10 @@
// search through all methods
int paramSize = parameterTypes.length;
- Constructor[] ctors = clazz.getConstructors();
+ Constructor<?>[] ctors = clazz.getConstructors();
for (int i = 0, size = ctors.length; i < size; i++) {
// compare parameters
- Class[] ctorParams = ctors[i].getParameterTypes();
+ Class<?>[] ctorParams = ctors[i].getParameterTypes();
int ctorParamSize = ctorParams.length;
if (ctorParamSize == paramSize) {
boolean match = true;
@@ -408,7 +417,7 @@
if (match) {
// get accessible version of method
- Constructor ctor = getAccessibleConstructor(ctors[i]);
+ Constructor<?> ctor = getAccessibleConstructor(ctors[i]);
if (ctor != null) {
try {
ctor.setAccessible(true);
@@ -417,7 +426,11 @@
* TODO: Why?
*/
}
- return ctor;
+ @SuppressWarnings("unchecked")
+ // Class.getConstructors() actually returns constructors
+ // of type T, so it is safe to cast.
+ Constructor<T> typedCtor = (Constructor<T>) ctor;
+ return typedCtor;
}
}
}
diff --git a/src/main/java/org/apache/commons/beanutils/ContextClassLoaderLocal.java b/src/main/java/org/apache/commons/beanutils/ContextClassLoaderLocal.java
index c16695e..8bf2c8f 100644
--- a/src/main/java/org/apache/commons/beanutils/ContextClassLoaderLocal.java
+++ b/src/main/java/org/apache/commons/beanutils/ContextClassLoaderLocal.java
@@ -50,14 +50,14 @@
* <p>Expected usage is as follows:<br>
* <pre>
* public class SomeClass {
- * private static final ContextClassLoaderLocal global
- * = new ContextClassLoaderLocal() {
- * protected Object initialValue() {
+ * private static final ContextClassLoaderLocal<String> global
+ * = new ContextClassLoaderLocal<String>() {
+ * protected String initialValue() {
* return new String("Initial value");
* };
*
* public void testGlobal() {
- * String s = (String) global.get();
+ * String s = global.get();
* System.out.println("global value:" + s);
* buf.set("New Value");
* }
@@ -97,13 +97,14 @@
* containers required each component to load the full set of classes it
* needs, ie avoided providing classes loaded via a "shared" classloader.</p>
*
+ * @param <T> the type of data stored in an instance
* @version $Id$
* @see java.lang.Thread#getContextClassLoader
*/
-public class ContextClassLoaderLocal {
- private final Map valueByClassLoader = new WeakHashMap();
+public class ContextClassLoaderLocal<T> {
+ private final Map<ClassLoader, T> valueByClassLoader = new WeakHashMap<ClassLoader, T>();
private boolean globalValueInitialized = false;
- private Object globalValue;
+ private T globalValue;
/**
* Construct a context classloader instance
@@ -125,7 +126,7 @@
*
* @return a new Object to be used as an initial value for this ContextClassLoaderLocal
*/
- protected Object initialValue() {
+ protected T initialValue() {
return null;
}
@@ -135,7 +136,7 @@
* This mechanism provides isolation for web apps deployed in the same container.
* @return the object currently associated with the context-classloader of the current thread.
*/
- public synchronized Object get() {
+ public synchronized T get() {
// synchronizing the whole method is a bit slower
// but guarantees no subtle threading problems, and there's no
// need to synchronize valueByClassLoader
@@ -147,7 +148,7 @@
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null) {
- Object value = valueByClassLoader.get(contextClassLoader);
+ T value = valueByClassLoader.get(contextClassLoader);
if ((value == null)
&& !valueByClassLoader.containsKey(contextClassLoader)) {
value = initialValue();
@@ -173,7 +174,7 @@
*
* @param value the object to be associated with the entrant thread's context classloader
*/
- public synchronized void set(Object value) {
+ public synchronized void set(T value) {
// synchronizing the whole method is a bit slower
// but guarentees no subtle threading problems
diff --git a/src/main/java/org/apache/commons/beanutils/ConvertUtils.java b/src/main/java/org/apache/commons/beanutils/ConvertUtils.java
index 9e6966d..c0b0897 100644
--- a/src/main/java/org/apache/commons/beanutils/ConvertUtils.java
+++ b/src/main/java/org/apache/commons/beanutils/ConvertUtils.java
@@ -247,7 +247,7 @@
*
* @see ConvertUtilsBean#convert(String, Class)
*/
- public static Object convert(String value, Class clazz) {
+ public static Object convert(String value, Class<?> clazz) {
return ConvertUtilsBean.getInstance().convert(value, clazz);
}
@@ -264,7 +264,7 @@
*
* @see ConvertUtilsBean#convert(String[], Class)
*/
- public static Object convert(String[] values, Class clazz) {
+ public static Object convert(String[] values, Class<?> clazz) {
return ConvertUtilsBean.getInstance().convert(values, clazz);
}
@@ -278,7 +278,7 @@
*
* @exception ConversionException if thrown by an underlying Converter
*/
- public static Object convert(Object value, Class targetType) {
+ public static Object convert(Object value, Class<?> targetType) {
return ConvertUtilsBean.getInstance().convert(value, targetType);
}
@@ -304,7 +304,7 @@
* @param clazz Class for which to remove a registered Converter
* @see ConvertUtilsBean#deregister(Class)
*/
- public static void deregister(Class clazz) {
+ public static void deregister(Class<?> clazz) {
ConvertUtilsBean.getInstance().deregister(clazz);
}
@@ -320,7 +320,7 @@
* @return The registered {@link Converter} or <code>null</code> if not found
* @see ConvertUtilsBean#lookup(Class)
*/
- public static Converter lookup(Class clazz) {
+ public static Converter lookup(Class<?> clazz) {
return ConvertUtilsBean.getInstance().lookup(clazz);
}
@@ -333,7 +333,7 @@
* @param targetType Class of the value to be converted to
* @return The registered {@link Converter} or <code>null</code> if not found
*/
- public static Converter lookup(Class sourceType, Class targetType) {
+ public static Converter lookup(Class<?> sourceType, Class<?> targetType) {
return ConvertUtilsBean.getInstance().lookup(sourceType, targetType);
}
@@ -348,8 +348,46 @@
* Converter
* @see ConvertUtilsBean#register(Converter, Class)
*/
- public static void register(Converter converter, Class clazz) {
+ public static void register(Converter converter, Class<?> clazz) {
ConvertUtilsBean.getInstance().register(converter, clazz);
}
+
+ /**
+ * Change primitive Class types to the associated wrapper class. This is
+ * useful for concrete converter implementations which typically treat
+ * primitive types like their corresponding wrapper types.
+ *
+ * @param type The class type to check.
+ * @return The converted type.
+ * @since 1.9
+ */
+ // All type casts are safe because the TYPE members of the wrapper types
+ // return their own class.
+ @SuppressWarnings("unchecked")
+ public static <T> Class<T> primitiveToWrapper(Class<T> type) {
+ if (type == null || !type.isPrimitive()) {
+ return type;
+ }
+
+ if (type == Integer.TYPE) {
+ return (Class<T>) Integer.class;
+ } else if (type == Double.TYPE) {
+ return (Class<T>) Double.class;
+ } else if (type == Long.TYPE) {
+ return (Class<T>) Long.class;
+ } else if (type == Boolean.TYPE) {
+ return (Class<T>) Boolean.class;
+ } else if (type == Float.TYPE) {
+ return (Class<T>) Float.class;
+ } else if (type == Short.TYPE) {
+ return (Class<T>) Short.class;
+ } else if (type == Byte.TYPE) {
+ return (Class<T>) Byte.class;
+ } else if (type == Character.TYPE) {
+ return (Class<T>) Character.class;
+ } else {
+ return type;
+ }
+ }
}
diff --git a/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean.java b/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean.java
index 5d7f7c0..3d78a94 100644
--- a/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean.java
+++ b/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean.java
@@ -145,7 +145,8 @@
* The set of {@link Converter}s that can be used to convert Strings
* into objects of a specified Class, keyed by the destination Class.
*/
- private final WeakFastHashMap converters = new WeakFastHashMap();
+ private final WeakFastHashMap<Class<?>, Converter> converters =
+ new WeakFastHashMap<Class<?>, Converter>();
/**
* The <code>Log</code> instance for this class.
@@ -454,11 +455,11 @@
return null;
} else {
Converter converter = lookup(String.class);
- return ((String) converter.convert(String.class, value));
+ return (converter.convert(String.class, value));
}
} else {
Converter converter = lookup(String.class);
- return ((String) converter.convert(String.class, value));
+ return (converter.convert(String.class, value));
}
}
@@ -468,13 +469,14 @@
* Convert the specified value to an object of the specified class (if
* possible). Otherwise, return a String representation of the value.
*
+ * @param <T> The desired target type of the conversion
* @param value Value to be converted (may be null)
* @param clazz Java class to be converted to (must not be null)
* @return The converted value
*
* @exception ConversionException if thrown by an underlying Converter
*/
- public Object convert(String value, Class clazz) {
+ public Object convert(String value, Class<?> clazz) {
if (log.isDebugEnabled()) {
log.debug("Convert string '" + value + "' to class '" +
@@ -505,9 +507,9 @@
*
* @exception ConversionException if thrown by an underlying Converter
*/
- public Object convert(String[] values, Class clazz) {
+ public Object convert(String[] values, Class<?> clazz) {
- Class type = clazz;
+ Class<?> type = clazz;
if (clazz.isArray()) {
type = clazz.getComponentType();
}
@@ -532,8 +534,9 @@
/**
- * <p>Convert the value to an object of the specified class (if
- * possible).</p>
+ * Convert the value to an object of the specified class (if
+ * possible). If no converter for the desired target type is registered,
+ * the passed in object is returned unchanged.
*
* @param value Value to be converted (may be null)
* @param targetType Class of the value to be converted to (must not be null)
@@ -541,9 +544,9 @@
*
* @exception ConversionException if thrown by an underlying Converter
*/
- public Object convert(Object value, Class targetType) {
+ public Object convert(Object value, Class<?> targetType) {
- Class sourceType = value == null ? null : value.getClass();
+ Class<?> sourceType = value == null ? null : value.getClass();
if (log.isDebugEnabled()) {
if (value == null) {
@@ -563,7 +566,7 @@
}
converted = converter.convert(targetType, value);
}
- if (targetType == String.class && converted != null &&
+ if (String.class.equals(targetType) && converted != null &&
!(converted instanceof String)) {
// NOTE: For backwards compatibility, if the Converter
@@ -789,9 +792,9 @@
* value used in the event of a conversion error
* @param defaultArraySize The size of the default array
*/
- private void registerArrayConverter(Class componentType, Converter componentConverter,
+ private void registerArrayConverter(Class<?> componentType, Converter componentConverter,
boolean throwException, int defaultArraySize) {
- Class arrayType = Array.newInstance(componentType, 0).getClass();
+ Class<?> arrayType = Array.newInstance(componentType, 0).getClass();
Converter arrayConverter = null;
if (throwException) {
arrayConverter = new ArrayConverter(arrayType, componentConverter);
@@ -802,7 +805,7 @@
}
/** strictly for convenience since it has same parameter order as Map.put */
- private void register(Class clazz, Converter converter) {
+ private void register(Class<?> clazz, Converter converter) {
register(new ConverterFacade(converter), clazz);
}
@@ -812,7 +815,7 @@
*
* @param clazz Class for which to remove a registered Converter
*/
- public void deregister(Class clazz) {
+ public void deregister(Class<?> clazz) {
converters.remove(clazz);
@@ -827,9 +830,9 @@
* @param clazz Class for which to return a registered Converter
* @return The registered {@link Converter} or <code>null</code> if not found
*/
- public Converter lookup(Class clazz) {
+ public Converter lookup(Class<?> clazz) {
- return ((Converter) converters.get(clazz));
+ return (converters.get(clazz));
}
@@ -842,7 +845,7 @@
* @param targetType Class of the value to be converted to
* @return The registered {@link Converter} or <code>null</code> if not found
*/
- public Converter lookup(Class sourceType, Class targetType) {
+ public Converter lookup(Class<?> sourceType, Class<?> targetType) {
if (targetType == null) {
throw new IllegalArgumentException("Target type is missing");
@@ -888,7 +891,7 @@
* @param clazz Destination class for conversions performed by this
* Converter
*/
- public void register(Converter converter, Class clazz) {
+ public void register(Converter converter, Class<?> clazz) {
converters.put(clazz, converter);
diff --git a/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean2.java b/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean2.java
index 0502d98..eb9890f 100644
--- a/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean2.java
+++ b/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean2.java
@@ -56,7 +56,7 @@
* @see ConvertUtilsBean#convert(String[], Class)
*/
@Override
- public Object convert(String value, Class clazz) {
+ public Object convert(String value, Class<?> clazz) {
return convert((Object)value, clazz);
}
@@ -71,7 +71,7 @@
* @see ConvertUtilsBean#convert(String[], Class)
*/
@Override
- public Object convert(String[] value, Class clazz) {
+ public Object convert(String[] value, Class<?> clazz) {
return convert((Object)value, clazz);
}
diff --git a/src/main/java/org/apache/commons/beanutils/Converter.java b/src/main/java/org/apache/commons/beanutils/Converter.java
index c68eebf..39465c1 100644
--- a/src/main/java/org/apache/commons/beanutils/Converter.java
+++ b/src/main/java/org/apache/commons/beanutils/Converter.java
@@ -43,6 +43,7 @@
* Convert the specified input object into an output object of the
* specified type.
*
+ * @param <T> the desired result type
* @param type Data type to which this value should be converted
* @param value The input value to be converted
* @return The converted value
@@ -50,7 +51,7 @@
* @exception ConversionException if conversion cannot be performed
* successfully
*/
- public Object convert(Class type, Object value);
+ public <T> T convert(Class<T> type, Object value);
}
diff --git a/src/main/java/org/apache/commons/beanutils/DynaBeanMapDecorator.java b/src/main/java/org/apache/commons/beanutils/DynaBeanMapDecorator.java
index 61557bc..5fcbcb9 100644
--- a/src/main/java/org/apache/commons/beanutils/DynaBeanMapDecorator.java
+++ b/src/main/java/org/apache/commons/beanutils/DynaBeanMapDecorator.java
@@ -16,14 +16,6 @@
*/
package org.apache.commons.beanutils;
-import java.util.Map;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Collection;
-import java.util.Collections;
/**
* <p>Decorates a {@link DynaBean} to provide <code>Map</code> behaviour.</p>
@@ -66,331 +58,44 @@
* and <code>values()</code> methods create an <b><i>unmodifiable</i></b>
* <code>Set</code> and it does not support the Map's <code>clear()</code>
* and <code>remove()</code> operations.</p>
+ * <p>For reasons of backwards compatibility, the generic types of this
+ * {@code Map} implementation are {@code <Object, Object>}. However, the
+ * keys of the map are typically strings.</p>
*
* @since BeanUtils 1.8.0
* @version $Id$
+ * @deprecated Use {@link DynaBeanPropertyMapDecorator} instead. When adding
+ * generics it turned out that it was not possible to use the correct type
+ * parameters without breaking backwards compatibility. Therefore, class
+ * {@code DynaBeanPropertyMapDecorator} was introduced as a replacement.
*/
-public class DynaBeanMapDecorator implements Map {
-
- private final DynaBean dynaBean;
- private final boolean readOnly;
- private transient Set keySet;
-
- // ------------------- Constructors ----------------------------------
+@Deprecated
+public class DynaBeanMapDecorator extends BaseDynaBeanMapDecorator<Object> {
+ /**
+ * Construct a Map for the specified {@link DynaBean}.
+ *
+ * @param dynaBean The dyna bean being decorated
+ * @param readOnly <code>true</code> if the Map is read only
+ * otherwise <code>false</code>
+ * @throws IllegalArgumentException if the {@link DynaBean} is null.
+ */
+ public DynaBeanMapDecorator(DynaBean dynaBean, boolean readOnly) {
+ super(dynaBean, readOnly);
+ }
/**
- * Constructs a read only Map for the specified
+ * Constructs a read only Map for the specified
* {@link DynaBean}.
*
* @param dynaBean The dyna bean being decorated
* @throws IllegalArgumentException if the {@link DynaBean} is null.
*/
public DynaBeanMapDecorator(DynaBean dynaBean) {
- this(dynaBean, true);
+ super(dynaBean);
}
- /**
- * Construct a Map for the specified {@link DynaBean}.
- *
- * @param dynaBean The dyna bean being decorated
- * @param readOnly <code>true</code> if the Mpa is read only
- * otherwise <code>false</code>
- * @throws IllegalArgumentException if the {@link DynaBean} is null.
- */
- public DynaBeanMapDecorator(DynaBean dynaBean, boolean readOnly) {
- if (dynaBean == null) {
- throw new IllegalArgumentException("DynaBean is null");
- }
- this.dynaBean = dynaBean;
- this.readOnly = readOnly;
+ @Override
+ protected Object convertKey(String propertyName) {
+ return propertyName;
}
-
-
- // ------------------- public Methods --------------------------------
-
-
- /**
- * Indicate whether the Map is read only.
- *
- * @return <code>true</code> if the Map is read only,
- * otherwise <code>false</code>.
- */
- public boolean isReadOnly() {
- return readOnly;
- }
-
- // ------------------- java.util.Map Methods -------------------------
-
- /**
- * clear() operation is not supported.
- *
- * @throws UnsupportedOperationException
- */
- public void clear() {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Indicate whether the {@link DynaBean} contains a specified
- * value for one (or more) of its properties.
- *
- * @param key The {@link DynaBean}'s property name
- * @return <code>true</code> if one of the {@link DynaBean}'s
- * properties contains a specified value.
- */
- public boolean containsKey(Object key) {
- DynaClass dynaClass = getDynaBean().getDynaClass();
- DynaProperty dynaProperty = dynaClass.getDynaProperty(toString(key));
- return (dynaProperty == null ? false : true);
- }
-
- /**
- * Indicates whether the decorated {@link DynaBean} contains
- * a specified value.
- *
- * @param value The value to check for.
- * @return <code>true</code> if one of the the {@link DynaBean}'s
- * properties contains the specified value, otherwise
- * <code>false</code>.
- */
- public boolean containsValue(Object value) {
- DynaProperty[] properties = getDynaProperties();
- for (int i = 0; i < properties.length; i++) {
- String key = properties[i].getName();
- Object prop = getDynaBean().get(key);
- if (value == null) {
- if (prop == null) {
- return true;
- }
- } else {
- if (value.equals(prop)) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * <p>Returns the Set of the property/value mappings
- * in the decorated {@link DynaBean}.</p>
- *
- * <p>Each element in the Set is a <code>Map.Entry</code>
- * type.</p>
- *
- * @return An unmodifiable set of the DynaBean
- * property name/value pairs
- */
- public Set entrySet() {
- DynaProperty[] properties = getDynaProperties();
- Set set = new HashSet(properties.length);
- for (int i = 0; i < properties.length; i++) {
- String key = properties[i].getName();
- Object value = getDynaBean().get(key);
- set.add(new MapEntry(key, value));
- }
- return Collections.unmodifiableSet(set);
- }
-
- /**
- * Return the value for the specified key from
- * the decorated {@link DynaBean}.
- *
- * @param key The {@link DynaBean}'s property name
- * @return The value for the specified property.
- */
- public Object get(Object key) {
- return getDynaBean().get(toString(key));
- }
-
- /**
- * Indicate whether the decorated {@link DynaBean} has
- * any properties.
- *
- * @return <code>true</code> if the {@link DynaBean} has
- * no properties, otherwise <code>false</code>.
- */
- public boolean isEmpty() {
- return (getDynaProperties().length == 0);
- }
-
- /**
- * <p>Returns the Set of the property
- * names in the decorated {@link DynaBean}.</p>
- *
- * <p><b>N.B.</b>For {@link DynaBean}s whose associated {@link DynaClass}
- * is a {@link MutableDynaClass} a new Set is created every
- * time, otherwise the Set is created only once and cached.</p>
- *
- * @return An unmodifiable set of the {@link DynaBean}s
- * property names.
- */
- public Set keySet() {
- if (keySet != null) {
- return keySet;
- }
-
- // Create a Set of the keys
- DynaProperty[] properties = getDynaProperties();
- Set set = new HashSet(properties.length);
- for (int i = 0; i < properties.length; i++) {
- set.add(properties[i].getName());
- }
- set = Collections.unmodifiableSet(set);
-
- // Cache the keySet if Not a MutableDynaClass
- DynaClass dynaClass = getDynaBean().getDynaClass();
- if (!(dynaClass instanceof MutableDynaClass)) {
- keySet = set;
- }
-
- return set;
-
- }
-
- /**
- * Set the value for the specified property in
- * the decorated {@link DynaBean}.
- *
- * @param key The {@link DynaBean}'s property name
- * @param value The value for the specified property.
- * @return The previous property's value.
- * @throws UnsupportedOperationException if
- * <code>isReadOnly()</code> is true.
- */
- public Object put(Object key, Object value) {
- if (isReadOnly()) {
- throw new UnsupportedOperationException("Map is read only");
- }
- String property = toString(key);
- Object previous = getDynaBean().get(property);
- getDynaBean().set(property, value);
- return previous;
- }
-
- /**
- * Copy the contents of a Map to the decorated {@link DynaBean}.
- *
- * @param map The Map of values to copy.
- * @throws UnsupportedOperationException if
- * <code>isReadOnly()</code> is true.
- */
- public void putAll(Map map) {
- if (isReadOnly()) {
- throw new UnsupportedOperationException("Map is read only");
- }
- Iterator keys = map.keySet().iterator();
- while (keys.hasNext()) {
- Object key = keys.next();
- put(key, map.get(key));
- }
- }
-
- /**
- * remove() operation is not supported.
- *
- * @param key The {@link DynaBean}'s property name
- * @return the value removed
- * @throws UnsupportedOperationException
- */
- public Object remove(Object key) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Returns the number properties in the decorated
- * {@link DynaBean}.
- * @return The number of properties.
- */
- public int size() {
- return getDynaProperties().length;
- }
-
- /**
- * Returns the set of property values in the
- * decorated {@link DynaBean}.
- *
- * @return Unmodifiable collection of values.
- */
- public Collection values() {
- DynaProperty[] properties = getDynaProperties();
- List values = new ArrayList(properties.length);
- for (int i = 0; i < properties.length; i++) {
- String key = properties[i].getName();
- Object value = getDynaBean().get(key);
- values.add(value);
- }
- return Collections.unmodifiableList(values);
- }
-
- // ------------------- protected Methods -----------------------------
-
- /**
- * Provide access to the underlying {@link DynaBean}
- * this Map decorates.
- *
- * @return the decorated {@link DynaBean}.
- */
- public DynaBean getDynaBean() {
- return dynaBean;
- }
-
- // ------------------- private Methods -------------------------------
-
- /**
- * Convenience method to retrieve the {@link DynaProperty}s
- * for this {@link DynaClass}.
- *
- * @return The an array of the {@link DynaProperty}s.
- */
- private DynaProperty[] getDynaProperties() {
- return getDynaBean().getDynaClass().getDynaProperties();
- }
-
- /**
- * Convenience method to convert an Object
- * to a String.
- *
- * @param obj The Object to convert
- * @return String representation of the object
- */
- private String toString(Object obj) {
- return (obj == null ? null : obj.toString());
- }
-
- /**
- * Map.Entry implementation.
- */
- private static class MapEntry implements Map.Entry {
- private final Object key;
- private final Object value;
- MapEntry(Object key, Object value) {
- this.key = key;
- this.value = value;
- }
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof Map.Entry)) {
- return false;
- }
- Map.Entry e = (Map.Entry)o;
- return ((key.equals(e.getKey())) &&
- (value == null ? e.getValue() == null
- : value.equals(e.getValue())));
- }
- @Override
- public int hashCode() {
- return key.hashCode() + (value == null ? 0 : value.hashCode());
- }
- public Object getKey() {
- return key;
- }
- public Object getValue() {
- return value;
- }
- public Object setValue(Object value) {
- throw new UnsupportedOperationException();
- }
- }
-
}
diff --git a/src/main/java/org/apache/commons/beanutils/DynaBeanPropertyMapDecorator.java b/src/main/java/org/apache/commons/beanutils/DynaBeanPropertyMapDecorator.java
new file mode 100644
index 0000000..a57d8ef
--- /dev/null
+++ b/src/main/java/org/apache/commons/beanutils/DynaBeanPropertyMapDecorator.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.beanutils;
+
+/**
+ * <p>Decorates a {@link DynaBean} to provide <code>Map</code> behavior.</p>
+ *
+ * <p>The motivation for this implementation is to provide access to {@link DynaBean}
+ * properties in technologies that are unaware of BeanUtils and {@link DynaBean}s -
+ * such as the expression languages of JSTL and JSF.</p>
+ *
+ * <p>This can be achieved either by wrapping the {@link DynaBean} prior to
+ * providing it to the technology to process or by providing a <code>Map</code>
+ * accessor method on the DynaBean implementation:
+ * <pre><code>
+ * public Map<String, Object> getMap() {
+ * return new DynaBeanPropertyMapDecorator(this);
+ * }</code></pre>
+ * </ul>
+ * </p>
+ *
+ * <p>This, for example, could be used in JSTL in the following way to access
+ * a DynaBean's <code>fooProperty</code>:
+ * <ul><li><code>${myDynaBean.<b>map</b>.fooProperty}</code></li></ul>
+ * </p>
+ *
+ * <h3>Usage</h3>
+ *
+ * <p>To decorate a {@link DynaBean} simply instantiate this class with the
+ * target {@link DynaBean}:</p>
+ *
+ * <ul><li><code>Map<String, Object> fooMap = new DynaBeanPropertyMapDecorator(fooDynaBean);</code></li></ul>
+ *
+ * <p>The above example creates a <b><i>read only</i></b> <code>Map</code>.
+ * To create a <code>Map</code> which can be modified, construct a
+ * <code>DynaBeanPropertyMapDecorator</code> with the <b><i>read only</i></b>
+ * attribute set to <code>false</code>:</p>
+ *
+ * <ul><li><code>Map<String, Object> fooMap = new DynaBeanPropertyMapDecorator(fooDynaBean, false);</code></li></ul>
+ *
+ * <h3>Limitations</h3>
+ * <p>In this implementation the <code>entrySet()</code>, <code>keySet()</code>
+ * and <code>values()</code> methods create an <b><i>unmodifiable</i></b>
+ * <code>Set</code> and it does not support the Map's <code>clear()</code>
+ * and <code>remove()</code> operations.</p>
+ *
+ * @since BeanUtils 1.9.0
+ * @version $Id$
+ */
+public class DynaBeanPropertyMapDecorator extends BaseDynaBeanMapDecorator<String> {
+ /**
+ * Construct a Map for the specified {@link DynaBean}.
+ *
+ * @param dynaBean The dyna bean being decorated
+ * @param readOnly <code>true</code> if the Map is read only
+ * otherwise <code>false</code>
+ * @throws IllegalArgumentException if the {@link DynaBean} is null.
+ */
+ public DynaBeanPropertyMapDecorator(DynaBean dynaBean, boolean readOnly) {
+ super(dynaBean, readOnly);
+ }
+
+ /**
+ * Constructs a read only Map for the specified
+ * {@link DynaBean}.
+ *
+ * @param dynaBean The dyna bean being decorated
+ * @throws IllegalArgumentException if the {@link DynaBean} is null.
+ */
+ public DynaBeanPropertyMapDecorator(DynaBean dynaBean) {
+ super(dynaBean);
+ }
+
+ @Override
+ protected String convertKey(String propertyName) {
+ return propertyName;
+ }
+}
diff --git a/src/main/java/org/apache/commons/beanutils/DynaProperty.java b/src/main/java/org/apache/commons/beanutils/DynaProperty.java
index 5f62ee7..33f78ac 100644
--- a/src/main/java/org/apache/commons/beanutils/DynaProperty.java
+++ b/src/main/java/org/apache/commons/beanutils/DynaProperty.java
@@ -20,9 +20,9 @@
import java.io.IOException;
-import java.io.Serializable;
-import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.List;
import java.util.Map;
@@ -84,7 +84,7 @@
* @param name Name of the property being described
* @param type Java class representing the property data type
*/
- public DynaProperty(String name, Class type) {
+ public DynaProperty(String name, Class<?> type) {
super();
this.name = name;
@@ -103,7 +103,7 @@
* @param type Java class representing the property data type
* @param contentType Class that all indexed or mapped elements are instances of
*/
- public DynaProperty(String name, Class type, Class contentType) {
+ public DynaProperty(String name, Class<?> type, Class<?> contentType) {
super();
this.name = name;
@@ -125,7 +125,7 @@
}
/** Property type */
- protected transient Class type = null;
+ protected transient Class<?> type = null;
/**
* <p>Gets the Java class representing the data type of the underlying property
* values.</p>
@@ -138,13 +138,13 @@
*
* @return the property type
*/
- public Class getType() {
+ public Class<?> getType() {
return (this.type);
}
/** The <em>(optional)</em> type of content elements for indexed <code>DynaProperty</code> */
- protected transient Class contentType;
+ protected transient Class<?> contentType;
/**
* Gets the <em>(optional)</em> type of the indexed content for <code>DynaProperty</code>'s
* that support this feature.
@@ -156,7 +156,7 @@
* @return the Class for the content type if this is an indexed <code>DynaProperty</code>
* and this feature is supported. Otherwise null.
*/
- public Class getContentType() {
+ public Class<?> getContentType() {
return contentType;
}
@@ -285,7 +285,7 @@
/**
* Write a class using safe encoding to workaround java 1.3 serialization bug.
*/
- private void writeAnyClass(Class clazz, ObjectOutputStream out) throws IOException {
+ private void writeAnyClass(Class<?> clazz, ObjectOutputStream out) throws IOException {
// safely write out any class
int primitiveType = 0;
if (Boolean.TYPE.equals(clazz)) {
@@ -341,7 +341,7 @@
/**
* Reads a class using safe encoding to workaround java 1.3 serialization bug.
*/
- private Class readAnyClass(ObjectInputStream in) throws IOException, ClassNotFoundException {
+ private Class<?> readAnyClass(ObjectInputStream in) throws IOException, ClassNotFoundException {
// read back type class safely
if (in.readBoolean()) {
// it's a type constant
@@ -365,7 +365,7 @@
} else {
// it's another class
- return ((Class) in.readObject());
+ return ((Class<?>) in.readObject());
}
}
}
\ No newline at end of file
diff --git a/src/main/java/org/apache/commons/beanutils/JDBCDynaClass.java b/src/main/java/org/apache/commons/beanutils/JDBCDynaClass.java
index 2c95e6a..e4da72f 100644
--- a/src/main/java/org/apache/commons/beanutils/JDBCDynaClass.java
+++ b/src/main/java/org/apache/commons/beanutils/JDBCDynaClass.java
@@ -61,13 +61,13 @@
* instances will be the same instances as those in the
* <code>properties</code> list.</p>
*/
- protected Map propertiesMap = new HashMap();
+ protected Map<String, DynaProperty> propertiesMap = new HashMap<String, DynaProperty>();
/**
* Cross Reference for column name --> dyna property name
* (needed when lowerCase option is true)
*/
- private Map columnNameXref;
+ private Map<String, String> columnNameXref;
// ------------------------------------------------------ DynaClass Methods
@@ -97,7 +97,7 @@
if (name == null) {
throw new IllegalArgumentException("No property name specified");
}
- return ((DynaProperty) propertiesMap.get(name));
+ return (propertiesMap.get(name));
}
@@ -150,7 +150,7 @@
* @exception SQLException if an exception was thrown trying to load
* the specified class
*/
- protected Class loadClass(String className) throws SQLException {
+ protected Class<?> loadClass(String className) throws SQLException {
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
@@ -190,7 +190,7 @@
String name = lowerCase ? columnName.toLowerCase() : columnName;
if (!name.equals(columnName)) {
if (columnNameXref == null) {
- columnNameXref = new HashMap();
+ columnNameXref = new HashMap<String, String>();
}
columnNameXref.put(name, columnName);
}
@@ -214,7 +214,7 @@
// Default to Object type if no class name could be retrieved
// from the metadata
- Class clazz = Object.class;
+ Class<?> clazz = Object.class;
if (className != null) {
clazz = loadClass(className);
}
@@ -236,7 +236,7 @@
protected void introspect(ResultSet resultSet) throws SQLException {
// Accumulate an ordered list of DynaProperties
- ArrayList list = new ArrayList();
+ ArrayList<DynaProperty> list = new ArrayList<DynaProperty>();
ResultSetMetaData metadata = resultSet.getMetaData();
int n = metadata.getColumnCount();
for (int i = 1; i <= n; i++) { // JDBC is one-relative!
@@ -248,7 +248,7 @@
// Convert this list into the internal data structures we need
properties =
- (DynaProperty[]) list.toArray(new DynaProperty[list.size()]);
+ list.toArray(new DynaProperty[list.size()]);
for (int i = 0; i < properties.length; i++) {
propertiesMap.put(properties[i].getName(), properties[i]);
}
@@ -270,7 +270,7 @@
throw new IllegalArgumentException("Invalid name '" + name + "'");
}
String columnName = getColumnName(name);
- Class type = property.getType();
+ Class<?> type = property.getType();
// java.sql.Date
if (type.equals(Date.class)) {
@@ -299,7 +299,7 @@
*/
protected String getColumnName(String name) {
if (columnNameXref != null && columnNameXref.containsKey(name)) {
- return (String)columnNameXref.get(name);
+ return columnNameXref.get(name);
} else {
return name;
}
diff --git a/src/main/java/org/apache/commons/beanutils/LazyDynaBean.java b/src/main/java/org/apache/commons/beanutils/LazyDynaBean.java
index 63ee35f..fc66423 100644
--- a/src/main/java/org/apache/commons/beanutils/LazyDynaBean.java
+++ b/src/main/java/org/apache/commons/beanutils/LazyDynaBean.java
@@ -16,15 +16,16 @@
*/
package org.apache.commons.beanutils;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.Date;
+import java.io.Serializable;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
-import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -141,10 +142,10 @@
* The <code>MutableDynaClass</code> "base class" that this DynaBean
* is associated with.
*/
- protected Map values;
+ protected Map<String, Object> values;
/** Map decorator for this DynaBean */
- private transient Map mapDecorator;
+ private transient Map<String, Object> mapDecorator;
/**
* The <code>MutableDynaClass</code> "base class" that this DynaBean
@@ -202,10 +203,10 @@
*
* @return a Map representation of this DynaBean
*/
- public Map getMap() {
+ public Map<String, Object> getMap() {
// cache the Map
if (mapDecorator == null) {
- mapDecorator = new DynaBeanMapDecorator(this);
+ mapDecorator = new DynaBeanPropertyMapDecorator(this);
}
return mapDecorator;
}
@@ -229,11 +230,11 @@
}
if (value instanceof Map) {
- return ((Map)value).size();
+ return ((Map<?, ?>)value).size();
}
if (value instanceof List) {
- return ((List)value).size();
+ return ((List<?>)value).size();
}
if ((value.getClass().isArray())) {
@@ -269,7 +270,7 @@
}
if (value instanceof Map) {
- return (((Map) value).containsKey(key));
+ return (((Map<?, ?>) value).containsKey(key));
}
return false;
@@ -353,7 +354,7 @@
if (indexedProperty.getClass().isArray()) {
return Array.get(indexedProperty, index);
} else if (indexedProperty instanceof List) {
- return ((List)indexedProperty).get(index);
+ return ((List<?>)indexedProperty).get(index);
} else {
throw new IllegalArgumentException
("Non-indexed property for '" + name + "[" + index + "]' "
@@ -394,7 +395,7 @@
// Get the value from the Map
if (mappedProperty instanceof Map) {
- return (((Map) mappedProperty).get(key));
+ return (((Map<?, ?>) mappedProperty).get(key));
} else {
throw new IllegalArgumentException
("Non-mapped property for '" + name + "(" + key + ")'"
@@ -437,7 +438,7 @@
}
if (value instanceof Map) {
- ((Map) value).remove(key);
+ ((Map<?, ?>) value).remove(key);
} else {
throw new IllegalArgumentException
("Non-mapped property for '" + name + "(" + key + ")'"
@@ -536,7 +537,10 @@
if (indexedProperty.getClass().isArray()) {
Array.set(indexedProperty, index, value);
} else if (indexedProperty instanceof List) {
- ((List)indexedProperty).set(index, value);
+ @SuppressWarnings("unchecked")
+ // Indexed properties are stored in a List<Object>
+ List<Object> values = (List<Object>) indexedProperty;
+ values.set(index, value);
} else {
throw new IllegalArgumentException
("Non-indexed property for '" + name + "[" + index + "]' "
@@ -577,7 +581,10 @@
}
// Set the value in the Map
- ((Map)mappedProperty).put(key, value);
+ @SuppressWarnings("unchecked")
+ // mapped properties are stored in a Map<String, Object>
+ Map<String, Object> valuesMap = (Map<String, Object>) mappedProperty;
+ valuesMap.put(key, value);
}
@@ -596,9 +603,11 @@
// Grow a List to the appropriate size
if (indexedProperty instanceof List) {
- List list = (List)indexedProperty;
+ @SuppressWarnings("unchecked")
+ // Indexed properties are stored as List<Object>
+ List<Object> list = (List<Object>)indexedProperty;
while (index >= list.size()) {
- Class contentType = getDynaClass().getDynaProperty(name).getContentType();
+ Class<?> contentType = getDynaClass().getDynaProperty(name).getContentType();
Object value = null;
if (contentType != null) {
value = createProperty(name+"["+list.size()+"]", contentType);
@@ -613,7 +622,7 @@
int length = Array.getLength(indexedProperty);
if (index >= length) {
- Class componentType = indexedProperty.getClass().getComponentType();
+ Class<?> componentType = indexedProperty.getClass().getComponentType();
Object newArray = Array.newInstance(componentType, (index + 1));
System.arraycopy(indexedProperty, 0, newArray, 0, length);
indexedProperty = newArray;
@@ -635,7 +644,7 @@
* @param type The class of the property
* @return The new value
*/
- protected Object createProperty(String name, Class type) {
+ protected Object createProperty(String name, Class<?> type) {
if (type == null) {
return null;
}
@@ -671,7 +680,7 @@
* @param type The class of the property
* @return The new value
*/
- protected Object createIndexedProperty(String name, Class type) {
+ protected Object createIndexedProperty(String name, Class<?> type) {
// Create the indexed object
Object indexedProperty = null;
@@ -713,7 +722,7 @@
* @param type The class of the property
* @return The new value
*/
- protected Object createMappedProperty(String name, Class type) {
+ protected Object createMappedProperty(String name, Class<?> type) {
// Create the mapped object
Object mappedProperty = null;
@@ -751,7 +760,7 @@
* @param type The class of the property
* @return The new value
*/
- protected Object createDynaBeanProperty(String name, Class type) {
+ protected Object createDynaBeanProperty(String name, Class<?> type) {
try {
return type.newInstance();
}
@@ -770,7 +779,7 @@
* @param type The class of the property
* @return The new value
*/
- protected Object createPrimitiveProperty(String name, Class type) {
+ protected Object createPrimitiveProperty(String name, Class<?> type) {
if (type == Boolean.TYPE) {
return Boolean.FALSE;
@@ -800,7 +809,7 @@
* @param type The class of the property
* @return The new value
*/
- protected Object createNumberProperty(String name, Class type) {
+ protected Object createNumberProperty(String name, Class<?> type) {
return null;
@@ -812,7 +821,7 @@
* @param type The class of the property
* @return The new value
*/
- protected Object createOtherProperty(String name, Class type) {
+ protected Object createOtherProperty(String name, Class<?> type) {
if (type == Object.class ||
type == String.class ||
@@ -839,28 +848,28 @@
* <p>Creates a new <code>ArrayList</code> for an 'indexed' property
* which doesn't exist.</p>
*
- * <p>This method shouls be overriden if an alternative <code>List</code>
+ * <p>This method should be overridden if an alternative <code>List</code>
* or <code>Array</code> implementation is required for 'indexed' properties.</p>
*
* @param name Name of the 'indexed property.
* @return The default value for an indexed property (java.util.ArrayList)
*/
protected Object defaultIndexedProperty(String name) {
- return new ArrayList();
+ return new ArrayList<Object>();
}
/**
* <p>Creates a new <code>HashMap</code> for a 'mapped' property
* which doesn't exist.</p>
*
- * <p>This method can be overriden if an alternative <code>Map</code>
+ * <p>This method can be overridden if an alternative <code>Map</code>
* implementation is required for 'mapped' properties.</p>
*
* @param name Name of the 'mapped property.
* @return The default value for a mapped property (java.util.HashMap)
*/
- protected Map defaultMappedProperty(String name) {
- return new HashMap();
+ protected Map<String, Object> defaultMappedProperty(String name) {
+ return new HashMap<String, Object>();
}
/**
@@ -893,7 +902,7 @@
* @return <code>true<code> if the source class is assignable to the
* destination class, otherwise <code>false</code>
*/
- protected boolean isAssignable(Class dest, Class source) {
+ protected boolean isAssignable(Class<?> dest, Class<?> source) {
if (dest.isAssignableFrom(source) ||
((dest == Boolean.TYPE) && (source == Boolean.class)) ||
@@ -915,8 +924,8 @@
* <p>Creates a new instance of the <code>Map</code>.</p>
* @return a new Map instance
*/
- protected Map newMap() {
- return new HashMap();
+ protected Map<String, Object> newMap() {
+ return new HashMap<String, Object>();
}
/**
diff --git a/src/main/java/org/apache/commons/beanutils/LazyDynaClass.java b/src/main/java/org/apache/commons/beanutils/LazyDynaClass.java
index 51edba3..8dd0890 100644
--- a/src/main/java/org/apache/commons/beanutils/LazyDynaClass.java
+++ b/src/main/java/org/apache/commons/beanutils/LazyDynaClass.java
@@ -79,7 +79,7 @@
* @param name Name of this DynaBean class
* @param dynaBeanClass The implementation class for new instances
*/
- public LazyDynaClass(String name, Class dynaBeanClass) {
+ public LazyDynaClass(String name, Class<?> dynaBeanClass) {
this(name, dynaBeanClass, null);
}
@@ -97,10 +97,10 @@
* Construct a new LazyDynaClass with the specified name, DynaBean class and properties.
*
* @param name Name of this DynaBean class
- * @param dynaBeanClass The implementation class for new intances
+ * @param dynaBeanClass The implementation class for new instances
* @param properties Property descriptors for the supported properties
*/
- public LazyDynaClass(String name, Class dynaBeanClass, DynaProperty properties[]) {
+ public LazyDynaClass(String name, Class<?> dynaBeanClass, DynaProperty properties[]) {
super(name, dynaBeanClass, properties);
}
@@ -177,7 +177,7 @@
* @exception IllegalStateException if this DynaClass is currently
* restricted, so no new properties can be added
*/
- public void add(String name, Class type) {
+ public void add(String name, Class<?> type) {
if (type == null) {
add(name);
} else {
@@ -206,7 +206,7 @@
*
* @exception UnsupportedOperationException anytime this method is called
*/
- public void add(String name, Class type, boolean readable, boolean writeable) {
+ public void add(String name, Class<?> type, boolean readable, boolean writeable) {
throw new java.lang.UnsupportedOperationException("readable/writable properties not supported");
}
@@ -320,7 +320,7 @@
throw new IllegalArgumentException("Property name is missing.");
}
- DynaProperty dynaProperty = (DynaProperty)propertiesMap.get(name);
+ DynaProperty dynaProperty = propertiesMap.get(name);
// If it doesn't exist and returnNull is false
// create a new DynaProperty
diff --git a/src/main/java/org/apache/commons/beanutils/LazyDynaList.java b/src/main/java/org/apache/commons/beanutils/LazyDynaList.java
index 32d6953..c52288d 100644
--- a/src/main/java/org/apache/commons/beanutils/LazyDynaList.java
+++ b/src/main/java/org/apache/commons/beanutils/LazyDynaList.java
@@ -16,11 +16,10 @@
*/
package org.apache.commons.beanutils;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.Collection;
-import java.util.Iterator;
import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Map;
/**
* <h2><i>Lazy</i> DynaBean List.</h2>
@@ -159,7 +158,7 @@
* @version $Id$
* @since 1.8.0
*/
-public class LazyDynaList extends ArrayList {
+public class LazyDynaList extends ArrayList<Object> {
/**
* The DynaClass of the List's elements.
@@ -179,12 +178,12 @@
/**
* The type of the List's elements.
*/
- private Class elementType;
+ private Class<?> elementType;
/**
* The DynaBean type of the List's elements.
*/
- private Class elementDynaBeanType;
+ private Class<?> elementDynaBeanType;
// ------------------- Constructors ------------------------------
@@ -224,7 +223,7 @@
*
* @param elementType The Type of the List's elements.
*/
- public LazyDynaList(Class elementType) {
+ public LazyDynaList(Class<?> elementType) {
super();
setElementType(elementType);
}
@@ -233,9 +232,9 @@
* Construct a LazyDynaList populated with the
* elements of a Collection.
*
- * @param collection The Collection to poulate the List from.
+ * @param collection The Collection to populate the List from.
*/
- public LazyDynaList(Collection collection) {
+ public LazyDynaList(Collection<?> collection) {
super(collection.size());
addAll(collection);
}
@@ -244,7 +243,7 @@
* Construct a LazyDynaList populated with the
* elements of an Array.
*
- * @param array The Array to poulate the List from.
+ * @param array The Array to populate the List from.
*/
public LazyDynaList(Object[] array) {
super(array.length);
@@ -299,7 +298,7 @@
* @return true if elements were added.
*/
@Override
- public boolean addAll(Collection collection) {
+ public boolean addAll(Collection<?> collection) {
if (collection == null || collection.size() == 0) {
return false;
@@ -307,9 +306,8 @@
ensureCapacity(size() + collection.size());
- Iterator iterator = collection.iterator();
- while (iterator.hasNext()) {
- add(iterator.next());
+ for (Object e : collection) {
+ add(e);
}
return true;
@@ -329,7 +327,7 @@
* @return true if elements were added.
*/
@Override
- public boolean addAll(int index, Collection collection) {
+ public boolean addAll(int index, Collection<?> collection) {
if (collection == null || collection.size() == 0) {
return false;
@@ -337,7 +335,7 @@
ensureCapacity((index > size() ? index : size()) + collection.size());
- // Call "tranform" with first element, before
+ // Call "transform" with first element, before
// List is "grown" to ensure the correct DynaClass
// is set.
if (size() == 0) {
@@ -346,9 +344,9 @@
growList(index);
- Iterator iterator = collection.iterator();
- while (iterator.hasNext()) {
- add(index++, iterator.next());
+ int currentIndex = index;
+ for (Object e : collection) {
+ add(currentIndex++, e);
}
return true;
@@ -435,36 +433,40 @@
/**
* <p>Converts the List to an Array of the specified type.</p>
*
+ * @param <T> The type of the array elements
* @param model The model for the type of array to return
* @return An Array of the elements in this List.
*/
@Override
- public Object[] toArray(Object[] model) {
+ public <T> T[] toArray(T[] model) {
- // Allocate the Array
- Class arrayType = model.getClass().getComponentType();
- Object[] array = (Object[])Array.newInstance(arrayType, size());
-
- if (size() == 0 && elementType == null) {
- return new LazyDynaBean[0];
- }
-
- if ((DynaBean.class.isAssignableFrom(arrayType))) {
- for (int i = 0; i < size(); i++) {
- array[i] = get(i);
- }
- return array;
+ Class<?> arrayType = model.getClass().getComponentType();
+ if ((DynaBean.class.isAssignableFrom(arrayType))
+ || (size() == 0 && elementType == null)) {
+ return super.toArray(model);
}
if ((arrayType.isAssignableFrom(elementType))) {
+ T[] array;
+ if (model.length >= size()) {
+ array = model;
+ } else {
+ @SuppressWarnings("unchecked")
+ // This is safe because we know the element type
+ T[] tempArray = (T[]) Array.newInstance(arrayType, size());
+ array = tempArray;
+ }
+
for (int i = 0; i < size(); i++) {
+ Object elem;
if (Map.class.isAssignableFrom(elementType)) {
- array[i] = ((LazyDynaMap)get(i)).getMap();
+ elem = ((LazyDynaMap) get(i)).getMap();
} else if (DynaBean.class.isAssignableFrom(elementType)) {
- array[i] = get(i);
+ elem = get(i);
} else {
- array[i] = ((WrapDynaBean)get(i)).getInstance();
+ elem = ((WrapDynaBean) get(i)).getInstance();
}
+ Array.set(array, i, elem);
}
return array;
}
@@ -504,7 +506,7 @@
* @exception IllegalArgumentException if the List already
* contains elements or the DynaClass is null.
*/
- public void setElementType(Class elementType) {
+ public void setElementType(Class<?> elementType) {
if (elementType == null) {
throw new IllegalArgumentException("Element Type is missing");
@@ -529,7 +531,7 @@
// Create a DynaBean
DynaBean dynaBean = null;
if (Map.class.isAssignableFrom(elementType)) {
- dynaBean = new LazyDynaMap((Map)object);
+ dynaBean = createDynaBeanForMapProperty(object);
this.elementDynaClass = dynaBean.getDynaClass();
} else if (DynaBean.class.isAssignableFrom(elementType)) {
dynaBean = (DynaBean)object;
@@ -623,14 +625,14 @@
* <li>DynaBeans are unchanged.</li>
* </li>
*
- * @param element The element to transformt.
+ * @param element The element to transformed.
* @param The DynaBean to store in the List.
*/
private DynaBean transform(Object element) {
DynaBean dynaBean = null;
- Class newDynaBeanType = null;
- Class newElementType = null;
+ Class<?> newDynaBeanType = null;
+ Class<?> newElementType = null;
// Create a new element
if (element == null) {
@@ -661,7 +663,7 @@
// Transform Object to a DynaBean
newElementType = element.getClass();
if (Map.class.isAssignableFrom(element.getClass())) {
- dynaBean = new LazyDynaMap((Map)element);
+ dynaBean = createDynaBeanForMapProperty(element);
} else if (DynaBean.class.isAssignableFrom(element.getClass())) {
dynaBean = (DynaBean)element;
} else {
@@ -692,6 +694,19 @@
}
/**
+ * Creates a new {@code LazyDynaMap} object for the given property value.
+ *
+ * @param value the property value
+ * @return the newly created {@code LazyDynaMap}
+ */
+ private LazyDynaMap createDynaBeanForMapProperty(Object value) {
+ @SuppressWarnings("unchecked")
+ // map properties are always stored as Map<String, Object>
+ Map<String, Object> valueMap = (Map<String, Object>) value;
+ return new LazyDynaMap(valueMap);
+ }
+
+ /**
* Return the DynaClass.
*/
private DynaClass getDynaClass() {
diff --git a/src/main/java/org/apache/commons/beanutils/LazyDynaMap.java b/src/main/java/org/apache/commons/beanutils/LazyDynaMap.java
index 3d9ddc7..da0e5e0 100644
--- a/src/main/java/org/apache/commons/beanutils/LazyDynaMap.java
+++ b/src/main/java/org/apache/commons/beanutils/LazyDynaMap.java
@@ -17,7 +17,6 @@
package org.apache.commons.beanutils;
import java.util.Map;
-import java.util.Iterator;
/**
* <p>Provides a <i>light weight</i> <code>DynaBean</code> facade to a <code>Map</code>
@@ -74,7 +73,7 @@
* Default Constructor.
*/
public LazyDynaMap() {
- this(null, (Map)null);
+ this(null, (Map<String, Object>)null);
}
/**
@@ -83,7 +82,7 @@
* @param name Name of this DynaBean class
*/
public LazyDynaMap(String name) {
- this(name, (Map)null);
+ this(name, (Map<String, Object>)null);
}
/**
@@ -91,7 +90,7 @@
*
* @param values The Map backing this <code>LazyDynaMap</code>
*/
- public LazyDynaMap(Map values) {
+ public LazyDynaMap(Map<String, Object> values) {
this(null, values);
}
@@ -101,7 +100,7 @@
* @param name Name of this DynaBean class
* @param values The Map backing this <code>LazyDynaMap</code>
*/
- public LazyDynaMap(String name, Map values) {
+ public LazyDynaMap(String name, Map<String, Object> values) {
this.name = name == null ? "LazyDynaMap" : name;
this.values = values == null ? newMap() : values;
this.dynaClass = this;
@@ -123,7 +122,7 @@
* @param properties Property descriptors for the supported properties
*/
public LazyDynaMap(String name, DynaProperty[] properties) {
- this(name, (Map)null);
+ this(name, (Map<String, Object>)null);
if (properties != null) {
for (int i = 0; i < properties.length; i++) {
add(properties[i]);
@@ -147,7 +146,7 @@
*
* @param values The new Map of values
*/
- public void setMap(Map values) {
+ public void setMap(Map<String, Object> values) {
this.values = values;
}
@@ -157,7 +156,7 @@
* @since 1.8.0
*/
@Override
- public Map getMap() {
+ public Map<String, Object> getMap() {
return values;
}
@@ -252,12 +251,11 @@
int i = 0;
DynaProperty[] properties = new DynaProperty[values.size()];
- Iterator iterator = values.keySet().iterator();
-
- while (iterator.hasNext()) {
- String name = (String)iterator.next();
+ for (Map.Entry<String, Object> e : values.entrySet()) {
+ String name = e.getKey();
Object value = values.get(name);
- properties[i++] = new DynaProperty(name, value == null ? null : value.getClass());
+ properties[i++] = new DynaProperty(name, value == null ? null
+ : value.getClass());
}
return properties;
@@ -272,9 +270,12 @@
public DynaBean newInstance() {
// Create a new instance of the Map
- Map newMap = null;
+ Map<String, Object> newMap = null;
try {
- newMap = getMap().getClass().newInstance();
+ @SuppressWarnings("unchecked")
+ // The new map is used as properties map
+ Map<String, Object> temp = getMap().getClass().newInstance();
+ newMap = temp;
} catch(Exception ex) {
newMap = newMap();
}
@@ -340,7 +341,7 @@
* @exception IllegalStateException if this DynaClass is currently
* restricted, so no new properties can be added
*/
- public void add(String name, Class type) {
+ public void add(String name, Class<?> type) {
if (name == null) {
throw new IllegalArgumentException("Property name is missing.");
@@ -380,7 +381,7 @@
*
* @exception UnsupportedOperationException anytime this method is called
*/
- public void add(String name, Class type, boolean readable, boolean writeable) {
+ public void add(String name, Class<?> type, boolean readable, boolean writeable) {
throw new java.lang.UnsupportedOperationException("readable/writable properties not supported");
}
diff --git a/src/main/java/org/apache/commons/beanutils/MappedPropertyDescriptor.java b/src/main/java/org/apache/commons/beanutils/MappedPropertyDescriptor.java
index 7710e5c..575b426 100644
--- a/src/main/java/org/apache/commons/beanutils/MappedPropertyDescriptor.java
+++ b/src/main/java/org/apache/commons/beanutils/MappedPropertyDescriptor.java
@@ -50,7 +50,7 @@
/**
* The underlying data type of the property we are describing.
*/
- private Reference mappedPropertyTypeRef;
+ private Reference<Class<?>> mappedPropertyTypeRef;
/**
* The reader method for this property (if any).
@@ -65,7 +65,7 @@
/**
* The parameter types array for the reader method signature.
*/
- private static final Class[] STRING_CLASS_PARAMETER = new Class[]{String.class};
+ private static final Class<?>[] STRING_CLASS_PARAMETER = new Class[]{String.class};
// ----------------------------------------------------------- Constructors
@@ -85,7 +85,7 @@
* @exception IntrospectionException if an exception occurs during
* introspection.
*/
- public MappedPropertyDescriptor(String propertyName, Class beanClass)
+ public MappedPropertyDescriptor(String propertyName, Class<?> beanClass)
throws IntrospectionException {
super(propertyName, null, null);
@@ -109,7 +109,7 @@
mappedReadMethod = getMethod(beanClass, "is" + base,
STRING_CLASS_PARAMETER);
}
- Class[] params = { String.class, mappedReadMethod.getReturnType() };
+ Class<?>[] params = { String.class, mappedReadMethod.getReturnType() };
mappedWriteMethod = getMethod(beanClass, "set" + base, params);
} catch (IntrospectionException e) {
/* Swallow IntrospectionException
@@ -151,7 +151,7 @@
* @exception IntrospectionException if an exception occurs during
* introspection.
*/
- public MappedPropertyDescriptor(String propertyName, Class beanClass,
+ public MappedPropertyDescriptor(String propertyName, Class<?> beanClass,
String mappedGetterName, String mappedSetterName)
throws IntrospectionException {
@@ -170,7 +170,7 @@
getMethod(beanClass, mappedGetterName, STRING_CLASS_PARAMETER);
if (mappedReadMethod != null) {
- Class[] params = { String.class, mappedReadMethod.getReturnType() };
+ Class<?>[] params = { String.class, mappedReadMethod.getReturnType() };
mappedWriteMethod =
getMethod(beanClass, mappedSetterName, params);
} else {
@@ -226,8 +226,8 @@
* <p>
* This is the type that will be returned by the mappedReadMethod.
*/
- public Class getMappedPropertyType() {
- return (Class)mappedPropertyTypeRef.get();
+ public Class<?> getMappedPropertyType() {
+ return mappedPropertyTypeRef.get();
}
/**
@@ -286,7 +286,7 @@
try {
Method mappedReadMethod = getMappedReadMethod();
Method mappedWriteMethod = getMappedWriteMethod();
- Class mappedPropertyType = null;
+ Class<?> mappedPropertyType = null;
if (mappedReadMethod != null) {
if (mappedReadMethod.getParameterTypes().length != 1) {
throw new IntrospectionException
@@ -301,7 +301,7 @@
}
if (mappedWriteMethod != null) {
- Class[] params = mappedWriteMethod.getParameterTypes();
+ Class<?>[] params = mappedWriteMethod.getParameterTypes();
if (params.length != 2) {
throw new IntrospectionException
("bad mapped write method arg count");
@@ -313,7 +313,7 @@
}
mappedPropertyType = params[1];
}
- mappedPropertyTypeRef = new SoftReference(mappedPropertyType);
+ mappedPropertyTypeRef = new SoftReference<Class<?>>(mappedPropertyType);
} catch (IntrospectionException ex) {
throw ex;
}
@@ -338,11 +338,11 @@
/**
* Find a method on a class with a specified number of parameters.
*/
- private static Method internalGetMethod(Class initial, String methodName,
+ private static Method internalGetMethod(Class<?> initial, String methodName,
int parameterCount) {
// For overridden methods we need to find the most derived version.
// So we start with the given class and walk up the superclass chain.
- for (Class clazz = initial; clazz != null; clazz = clazz.getSuperclass()) {
+ for (Class<?> clazz = initial; clazz != null; clazz = clazz.getSuperclass()) {
Method[] methods = clazz.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
@@ -365,7 +365,7 @@
// Now check any inherited interfaces. This is necessary both when
// the argument class is itself an interface, and when the argument
// class is an abstract class.
- Class[] interfaces = initial.getInterfaces();
+ Class<?>[] interfaces = initial.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
Method method = internalGetMethod(interfaces[i], methodName, parameterCount);
if (method != null) {
@@ -379,7 +379,7 @@
/**
* Find a method on a class with a specified number of parameters.
*/
- private static Method getMethod(Class clazz, String methodName, int parameterCount)
+ private static Method getMethod(Class<?> clazz, String methodName, int parameterCount)
throws IntrospectionException {
if (methodName == null) {
return null;
@@ -398,7 +398,7 @@
/**
* Find a method on a class with a specified parameter list.
*/
- private static Method getMethod(Class clazz, String methodName, Class[] parameterTypes)
+ private static Method getMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes)
throws IntrospectionException {
if (methodName == null) {
return null;
@@ -427,21 +427,21 @@
private static class MappedMethodReference {
private String className;
private String methodName;
- private Reference methodRef;
- private Reference classRef;
- private Reference writeParamTypeRef0;
- private Reference writeParamTypeRef1;
+ private Reference<Method> methodRef;
+ private Reference<Class<?>> classRef;
+ private Reference<Class<?>> writeParamTypeRef0;
+ private Reference<Class<?>> writeParamTypeRef1;
private String[] writeParamClassNames;
MappedMethodReference(Method m) {
if (m != null) {
className = m.getDeclaringClass().getName();
methodName = m.getName();
- methodRef = new SoftReference(m);
- classRef = new WeakReference(m.getDeclaringClass());
- Class[] types = m.getParameterTypes();
+ methodRef = new SoftReference<Method>(m);
+ classRef = new WeakReference<Class<?>>(m.getDeclaringClass());
+ Class<?>[] types = m.getParameterTypes();
if (types.length == 2) {
- writeParamTypeRef0 = new WeakReference(types[0]);
- writeParamTypeRef1 = new WeakReference(types[1]);
+ writeParamTypeRef0 = new WeakReference<Class<?>>(types[0]);
+ writeParamTypeRef1 = new WeakReference<Class<?>>(types[1]);
writeParamClassNames = new String[2];
writeParamClassNames[0] = types[0].getName();
writeParamClassNames[1] = types[1].getName();
@@ -452,34 +452,34 @@
if (methodRef == null) {
return null;
}
- Method m = (Method)methodRef.get();
+ Method m = methodRef.get();
if (m == null) {
- Class clazz = (Class)classRef.get();
+ Class<?> clazz = classRef.get();
if (clazz == null) {
clazz = reLoadClass();
if (clazz != null) {
- classRef = new WeakReference(clazz);
+ classRef = new WeakReference<Class<?>>(clazz);
}
}
if (clazz == null) {
throw new RuntimeException("Method " + methodName + " for " +
className + " could not be reconstructed - class reference has gone");
}
- Class[] paramTypes = null;
+ Class<?>[] paramTypes = null;
if (writeParamClassNames != null) {
paramTypes = new Class[2];
- paramTypes[0] = (Class)writeParamTypeRef0.get();
+ paramTypes[0] = writeParamTypeRef0.get();
if (paramTypes[0] == null) {
paramTypes[0] = reLoadClass(writeParamClassNames[0]);
if (paramTypes[0] != null) {
- writeParamTypeRef0 = new WeakReference(paramTypes[0]);
+ writeParamTypeRef0 = new WeakReference<Class<?>>(paramTypes[0]);
}
}
- paramTypes[1] = (Class)writeParamTypeRef1.get();
+ paramTypes[1] = writeParamTypeRef1.get();
if (paramTypes[1] == null) {
paramTypes[1] = reLoadClass(writeParamClassNames[1]);
if (paramTypes[1] != null) {
- writeParamTypeRef1 = new WeakReference(paramTypes[1]);
+ writeParamTypeRef1 = new WeakReference<Class<?>>(paramTypes[1]);
}
}
} else {
@@ -493,7 +493,7 @@
throw new RuntimeException("Method " + methodName + " for " +
className + " could not be reconstructed - method not found");
}
- methodRef = new SoftReference(m);
+ methodRef = new SoftReference<Method>(m);
}
return m;
}
@@ -501,14 +501,14 @@
/**
* Try to re-load the class
*/
- private Class reLoadClass() {
+ private Class<?> reLoadClass() {
return reLoadClass(className);
}
/**
* Try to re-load the class
*/
- private Class reLoadClass(String name) {
+ private Class<?> reLoadClass(String name) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
diff --git a/src/main/java/org/apache/commons/beanutils/MethodUtils.java b/src/main/java/org/apache/commons/beanutils/MethodUtils.java
index e7cadc7..525518d 100644
--- a/src/main/java/org/apache/commons/beanutils/MethodUtils.java
+++ b/src/main/java/org/apache/commons/beanutils/MethodUtils.java
@@ -32,7 +32,7 @@
/**
- * <p> Utility reflection methods focussed on methods in general rather than properties in particular. </p>
+ * <p> Utility reflection methods focused on methods in general rather than properties in particular. </p>
*
* <h3>Known Limitations</h3>
* <h4>Accessing Public Methods In A Default Access Superclass</h4>
@@ -77,7 +77,7 @@
private static boolean CACHE_METHODS = true;
/** An empty class array */
- private static final Class[] EMPTY_CLASS_PARAMETERS = new Class[0];
+ private static final Class<?>[] EMPTY_CLASS_PARAMETERS = new Class[0];
/** An empty object array */
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
@@ -101,7 +101,8 @@
* class via different classloaders will generate non-equal MethodDescriptor
* objects and hence end up with different entries in the map.
*/
- private static final Map cache = Collections.synchronizedMap(new WeakHashMap());
+ private static final Map<MethodDescriptor, Reference<Method>> cache = Collections
+ .synchronizedMap(new WeakHashMap<MethodDescriptor, Reference<Method>>());
// --------------------------------------------------------- Public Methods
@@ -214,7 +215,7 @@
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
- Class[] parameterTypes = new Class[arguments];
+ Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
@@ -253,7 +254,7 @@
Object object,
String methodName,
Object[] args,
- Class[] parameterTypes)
+ Class<?>[] parameterTypes)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -344,7 +345,7 @@
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
- Class[] parameterTypes = new Class[arguments];
+ Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
@@ -376,7 +377,7 @@
Object object,
String methodName,
Object[] args,
- Class[] parameterTypes)
+ Class<?>[] parameterTypes)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -423,10 +424,10 @@
* @since 1.8.0
*/
public static Object invokeExactStaticMethod(
- Class objectClass,
+ Class<?> objectClass,
String methodName,
Object[] args,
- Class[] parameterTypes)
+ Class<?>[] parameterTypes)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -481,7 +482,7 @@
* @since 1.8.0
*/
public static Object invokeStaticMethod(
- Class objectClass,
+ Class<?> objectClass,
String methodName,
Object arg)
throws
@@ -524,7 +525,7 @@
* @since 1.8.0
*/
public static Object invokeStaticMethod(
- Class objectClass,
+ Class<?> objectClass,
String methodName,
Object[] args)
throws
@@ -536,7 +537,7 @@
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
- Class[] parameterTypes = new Class[arguments];
+ Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
@@ -573,10 +574,10 @@
* @since 1.8.0
*/
public static Object invokeStaticMethod(
- Class objectClass,
+ Class<?> objectClass,
String methodName,
Object[] args,
- Class[] parameterTypes)
+ Class<?>[] parameterTypes)
throws
NoSuchMethodException,
IllegalAccessException,
@@ -623,7 +624,7 @@
* @since 1.8.0
*/
public static Object invokeExactStaticMethod(
- Class objectClass,
+ Class<?> objectClass,
String methodName,
Object arg)
throws
@@ -656,7 +657,7 @@
* @since 1.8.0
*/
public static Object invokeExactStaticMethod(
- Class objectClass,
+ Class<?> objectClass,
String methodName,
Object[] args)
throws
@@ -668,7 +669,7 @@
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
- Class[] parameterTypes = new Class[arguments];
+ Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
@@ -697,11 +698,11 @@
* @return The accessible method
*/
public static Method getAccessibleMethod(
- Class clazz,
+ Class<?> clazz,
String methodName,
- Class parameterType) {
+ Class<?> parameterType) {
- Class[] parameterTypes = {parameterType};
+ Class<?>[] parameterTypes = {parameterType};
return getAccessibleMethod(clazz, methodName, parameterTypes);
}
@@ -719,9 +720,9 @@
* @return The accessible method
*/
public static Method getAccessibleMethod(
- Class clazz,
+ Class<?> clazz,
String methodName,
- Class[] parameterTypes) {
+ Class<?>[] parameterTypes) {
try {
MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, true);
@@ -770,7 +771,7 @@
* @return The accessible method
* @since 1.8.0
*/
- public static Method getAccessibleMethod(Class clazz, Method method) {
+ public static Method getAccessibleMethod(Class<?> clazz, Method method) {
// Make sure we have a method to check
if (method == null) {
@@ -802,7 +803,7 @@
}
String methodName = method.getName();
- Class[] parameterTypes = method.getParameterTypes();
+ Class<?>[] parameterTypes = method.getParameterTypes();
// Check the implemented interfaces and subinterfaces
method =
@@ -833,9 +834,9 @@
* @param parameterTypes The parameter type signatures
*/
private static Method getAccessibleMethodFromSuperclass
- (Class clazz, String methodName, Class[] parameterTypes) {
+ (Class<?> clazz, String methodName, Class<?>[] parameterTypes) {
- Class parentClazz = clazz.getSuperclass();
+ Class<?> parentClazz = clazz.getSuperclass();
while (parentClazz != null) {
if (Modifier.isPublic(parentClazz.getModifiers())) {
try {
@@ -864,7 +865,7 @@
* @param parameterTypes The parameter type signatures
*/
private static Method getAccessibleMethodFromInterfaceNest
- (Class clazz, String methodName, Class[] parameterTypes) {
+ (Class<?> clazz, String methodName, Class<?>[] parameterTypes) {
Method method = null;
@@ -872,7 +873,7 @@
for (; clazz != null; clazz = clazz.getSuperclass()) {
// Check the implemented interfaces of the parent class
- Class[] interfaces = clazz.getInterfaces();
+ Class<?>[] interfaces = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
// Is this interface public?
@@ -917,7 +918,7 @@
* In other words, it finds a method with the given name
* that will take the parameters given.<p>
*
- * <p>This method is slightly undeterminstic since it loops
+ * <p>This method is slightly undeterministic since it loops
* through methods names and return the first matching method.</p>
*
* <p>This method is used by
@@ -934,9 +935,9 @@
* @return The accessible method
*/
public static Method getMatchingAccessibleMethod(
- Class clazz,
+ Class<?> clazz,
String methodName,
- Class[] parameterTypes) {
+ Class<?>[] parameterTypes) {
// trace logging
Log log = LogFactory.getLog(MethodUtils.class);
if (log.isTraceEnabled()) {
@@ -981,7 +982,7 @@
}
// compare parameters
- Class[] methodsParams = methods[i].getParameterTypes();
+ Class<?>[] methodsParams = methods[i].getParameterTypes();
int methodParamSize = methodsParams.length;
if (methodParamSize == paramSize) {
boolean match = true;
@@ -1094,11 +1095,11 @@
* @param destArgs The destination arguments
* @return The total transformation cost
*/
- private static float getTotalTransformationCost(Class[] srcArgs, Class[] destArgs) {
+ private static float getTotalTransformationCost(Class<?>[] srcArgs, Class<?>[] destArgs) {
float totalCost = 0.0f;
for (int i = 0; i < srcArgs.length; i++) {
- Class srcClass, destClass;
+ Class<?> srcClass, destClass;
srcClass = srcArgs[i];
destClass = destArgs[i];
totalCost += getObjectTransformationCost(srcClass, destClass);
@@ -1115,11 +1116,11 @@
* @param destClass The destination class
* @return The cost of transforming an object
*/
- private static float getObjectTransformationCost(Class srcClass, Class destClass) {
+ private static float getObjectTransformationCost(Class<?> srcClass, Class<?> destClass) {
float cost = 0.0f;
while (srcClass != null && !destClass.equals(srcClass)) {
if (destClass.isPrimitive()) {
- Class destClassWrapperClazz = getPrimitiveWrapper(destClass);
+ Class<?> destClassWrapperClazz = getPrimitiveWrapper(destClass);
if (destClassWrapperClazz != null && destClassWrapperClazz.equals(srcClass)) {
cost += 0.25f;
break;
@@ -1164,9 +1165,9 @@
* @param parameterType the type of parameter accepted by the method
* @param parameterization the type of parameter being tested
*
- * @return true if the assignement is compatible.
+ * @return true if the assignment is compatible.
*/
- public static final boolean isAssignmentCompatible(Class parameterType, Class parameterization) {
+ public static final boolean isAssignmentCompatible(Class<?> parameterType, Class<?> parameterization) {
// try plain assignment
if (parameterType.isAssignableFrom(parameterization)) {
return true;
@@ -1175,7 +1176,7 @@
if (parameterType.isPrimitive()) {
// this method does *not* do widening - you must specify exactly
// is this the right behaviour?
- Class parameterWrapperClazz = getPrimitiveWrapper(parameterType);
+ Class<?> parameterWrapperClazz = getPrimitiveWrapper(parameterType);
if (parameterWrapperClazz != null) {
return parameterWrapperClazz.equals(parameterization);
}
@@ -1191,7 +1192,7 @@
* @return the wrapper type associated with the given primitive
* or null if no match is found
*/
- public static Class getPrimitiveWrapper(Class primitiveType) {
+ public static Class<?> getPrimitiveWrapper(Class<?> primitiveType) {
// does anyone know a better strategy than comparing names?
if (boolean.class.equals(primitiveType)) {
return Boolean.class;
@@ -1222,7 +1223,7 @@
* @return the primitive type class corresponding to the given wrapper class,
* null if no match is found
*/
- public static Class getPrimitiveType(Class wrapperType) {
+ public static Class<?> getPrimitiveType(Class<?> wrapperType) {
// does anyone know a better strategy than comparing names?
if (Boolean.class.equals(wrapperType)) {
return boolean.class;
@@ -1255,9 +1256,9 @@
* @param clazz the class to find a representation for, not null
* @return the original class if it not a primitive. Otherwise the wrapper class. Not null
*/
- public static Class toNonPrimitiveClass(Class clazz) {
+ public static Class<?> toNonPrimitiveClass(Class<?> clazz) {
if (clazz.isPrimitive()) {
- Class primitiveClazz = MethodUtils.getPrimitiveWrapper(clazz);
+ Class<?> primitiveClazz = MethodUtils.getPrimitiveWrapper(clazz);
// the above method returns
if (primitiveClazz != null) {
return primitiveClazz;
@@ -1278,9 +1279,9 @@
*/
private static Method getCachedMethod(MethodDescriptor md) {
if (CACHE_METHODS) {
- Reference methodRef = (Reference)cache.get(md);
+ Reference<Method> methodRef = cache.get(md);
if (methodRef != null) {
- return (Method)methodRef.get();
+ return methodRef.get();
}
}
return null;
@@ -1295,7 +1296,7 @@
private static void cacheMethod(MethodDescriptor md, Method method) {
if (CACHE_METHODS) {
if (method != null) {
- cache.put(md, new WeakReference(method));
+ cache.put(md, new WeakReference<Method>(method));
}
}
}
@@ -1304,9 +1305,9 @@
* Represents the key to looking up a Method by reflection.
*/
private static class MethodDescriptor {
- private final Class cls;
+ private final Class<?> cls;
private final String methodName;
- private final Class[] paramTypes;
+ private final Class<?>[] paramTypes;
private final boolean exact;
private final int hashCode;
@@ -1315,10 +1316,10 @@
*
* @param cls the class to reflect, must not be null
* @param methodName the method name to obtain
- * @param paramTypes the array of classes representing the paramater types
+ * @param paramTypes the array of classes representing the parameter types
* @param exact whether the match has to be exact.
*/
- public MethodDescriptor(Class cls, String methodName, Class[] paramTypes, boolean exact) {
+ public MethodDescriptor(Class<?> cls, String methodName, Class<?>[] paramTypes, boolean exact) {
if (cls == null) {
throw new IllegalArgumentException("Class cannot be null");
}
diff --git a/src/main/java/org/apache/commons/beanutils/MutableDynaClass.java b/src/main/java/org/apache/commons/beanutils/MutableDynaClass.java
index 2381434..e61d9c0 100644
--- a/src/main/java/org/apache/commons/beanutils/MutableDynaClass.java
+++ b/src/main/java/org/apache/commons/beanutils/MutableDynaClass.java
@@ -60,7 +60,7 @@
* @exception IllegalStateException if this DynaClass is currently
* restricted, so no new properties can be added
*/
- public void add(String name, Class type);
+ public void add(String name, Class<?> type);
/**
@@ -79,7 +79,7 @@
* @exception IllegalStateException if this DynaClass is currently
* restricted, so no new properties can be added
*/
- public void add(String name, Class type, boolean readable,
+ public void add(String name, Class<?> type, boolean readable,
boolean writeable);
diff --git a/src/main/java/org/apache/commons/beanutils/PropertyUtils.java b/src/main/java/org/apache/commons/beanutils/PropertyUtils.java
index 2228771..4024ffc 100644
--- a/src/main/java/org/apache/commons/beanutils/PropertyUtils.java
+++ b/src/main/java/org/apache/commons/beanutils/PropertyUtils.java
@@ -203,7 +203,7 @@
* propety cannot be found
* @see PropertyUtilsBean#describe
*/
- public static Map describe(Object bean)
+ public static Map<String, Object> describe(Object bean)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
@@ -344,7 +344,7 @@
* @deprecated This method should not be exposed
*/
@Deprecated
- public static FastHashMap getMappedPropertyDescriptors(Class beanClass) {
+ public static FastHashMap getMappedPropertyDescriptors(Class<?> beanClass) {
return PropertyUtilsBean.getInstance().getMappedPropertyDescriptors(beanClass);
@@ -478,7 +478,7 @@
* @see PropertyUtilsBean#getPropertyDescriptors(Class)
*/
public static PropertyDescriptor[]
- getPropertyDescriptors(Class beanClass) {
+ getPropertyDescriptors(Class<?> beanClass) {
return PropertyUtilsBean.getInstance().getPropertyDescriptors(beanClass);
@@ -527,7 +527,7 @@
* propety cannot be found
* @see PropertyUtilsBean#getPropertyEditorClass(Object,String)
*/
- public static Class getPropertyEditorClass(Object bean, String name)
+ public static Class<?> getPropertyEditorClass(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
@@ -560,7 +560,7 @@
* propety cannot be found
* @see PropertyUtilsBean#getPropertyType(Object, String)
*/
- public static Class getPropertyType(Object bean, String name)
+ public static Class<?> getPropertyType(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
diff --git a/src/main/java/org/apache/commons/beanutils/PropertyUtilsBean.java b/src/main/java/org/apache/commons/beanutils/PropertyUtilsBean.java
index d35104a..494ab50 100644
--- a/src/main/java/org/apache/commons/beanutils/PropertyUtilsBean.java
+++ b/src/main/java/org/apache/commons/beanutils/PropertyUtilsBean.java
@@ -30,6 +30,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import org.apache.commons.beanutils.expression.DefaultResolver;
import org.apache.commons.beanutils.expression.Resolver;
@@ -112,10 +113,10 @@
* The cache of PropertyDescriptor arrays for beans we have already
* introspected, keyed by the java.lang.Class of this object.
*/
- private WeakFastHashMap descriptorsCache = null;
- private WeakFastHashMap mappedDescriptorsCache = null;
- private static final Class[] EMPTY_CLASS_PARAMETERS = new Class[0];
- private static final Class[] LIST_CLASS_PARAMETER = new Class[] {java.util.List.class};
+ private WeakFastHashMap<Class<?>, PropertyDescriptor[]> descriptorsCache = null;
+ private WeakFastHashMap<Class<?>, FastHashMap> mappedDescriptorsCache = null;
+ private static final Class<?>[] EMPTY_CLASS_PARAMETERS = new Class[0];
+ private static final Class<?>[] LIST_CLASS_PARAMETER = new Class[] {java.util.List.class};
/** An empty object array */
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
@@ -127,9 +128,9 @@
/** Base constructor */
public PropertyUtilsBean() {
- descriptorsCache = new WeakFastHashMap();
+ descriptorsCache = new WeakFastHashMap<Class<?>, PropertyDescriptor[]>();
descriptorsCache.setFast(true);
- mappedDescriptorsCache = new WeakFastHashMap();
+ mappedDescriptorsCache = new WeakFastHashMap<Class<?>, FastHashMap>();
mappedDescriptorsCache.setFast(true);
}
@@ -253,9 +254,9 @@
}
}
} else if (orig instanceof Map) {
- Iterator entries = ((Map) orig).entrySet().iterator();
+ Iterator<?> entries = ((Map<?, ?>) orig).entrySet().iterator();
while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
+ Map.Entry<?, ?> entry = (Entry<?, ?>) entries.next();
String name = (String)entry.getKey();
if (isWriteable(dest, name)) {
try {
@@ -315,14 +316,14 @@
* @exception NoSuchMethodException if an accessor method for this
* propety cannot be found
*/
- public Map describe(Object bean)
+ public Map<String, Object> describe(Object bean)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
if (bean == null) {
throw new IllegalArgumentException("No bean specified");
}
- Map description = new HashMap();
+ Map<String, Object> description = new HashMap<String, Object>();
if (bean instanceof DynaBean) {
DynaProperty[] descriptors =
((DynaBean) bean).getDynaClass().getDynaProperties();
@@ -438,7 +439,7 @@
if (bean.getClass().isArray()) {
return Array.get(bean, index);
} else if (bean instanceof List) {
- return ((List)bean).get(index);
+ return ((List<?>)bean).get(index);
}
}
if (name == null) {
@@ -502,7 +503,7 @@
"' is not indexed on bean class '" + bean.getClass() + "'");
} else {
//get the List's value
- return ((java.util.List) value).get(index);
+ return ((java.util.List<?>) value).get(index);
}
} else {
//get the array's value
@@ -646,7 +647,7 @@
Object invokeResult = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY);
/* test and fetch from the map */
if (invokeResult instanceof java.util.Map) {
- result = ((java.util.Map)invokeResult).get(key);
+ result = ((java.util.Map<?, ?>)invokeResult).get(key);
}
} else {
throw new NoSuchMethodException("Property '" + name +
@@ -669,14 +670,14 @@
* @deprecated This method should not be exposed
*/
@Deprecated
- public FastHashMap getMappedPropertyDescriptors(Class beanClass) {
+ public FastHashMap getMappedPropertyDescriptors(Class<?> beanClass) {
if (beanClass == null) {
return null;
}
// Look up any cached descriptors for this bean class
- return (FastHashMap) mappedDescriptorsCache.get(beanClass);
+ return mappedDescriptorsCache.get(beanClass);
}
@@ -737,7 +738,7 @@
String next = resolver.next(name);
Object nestedBean = null;
if (bean instanceof Map) {
- nestedBean = getPropertyOfMapBean((Map) bean, next);
+ nestedBean = getPropertyOfMapBean((Map<?, ?>) bean, next);
} else if (resolver.isMapped(next)) {
nestedBean = getMappedProperty(bean, next);
} else if (resolver.isIndexed(next)) {
@@ -755,7 +756,7 @@
}
if (bean instanceof Map) {
- bean = getPropertyOfMapBean((Map) bean, name);
+ bean = getPropertyOfMapBean((Map<?, ?>) bean, name);
} else if (resolver.isMapped(name)) {
bean = getMappedProperty(bean, name);
} else if (resolver.isIndexed(name)) {
@@ -791,7 +792,7 @@
* no simple method is available.
* @since 1.8.0
*/
- protected Object getPropertyOfMapBean(Map bean, String propertyName)
+ protected Object getPropertyOfMapBean(Map<?, ?> bean, String propertyName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
@@ -954,7 +955,7 @@
* @exception IllegalArgumentException if <code>beanClass</code> is null
*/
public PropertyDescriptor[]
- getPropertyDescriptors(Class beanClass) {
+ getPropertyDescriptors(Class<?> beanClass) {
if (beanClass == null) {
throw new IllegalArgumentException("No bean class specified");
@@ -963,7 +964,7 @@
// Look up any cached descriptors for this bean class
PropertyDescriptor[] descriptors = null;
descriptors =
- (PropertyDescriptor[]) descriptorsCache.get(beanClass);
+ descriptorsCache.get(beanClass);
if (descriptors != null) {
return (descriptors);
}
@@ -1031,7 +1032,7 @@
Method[] methods = beanClass.getMethods();
for (int j = 0; j < methods.length; j++) {
if (methods[j].getName().equals(methodName)) {
- Class[] parameterTypes = methods[j].getParameterTypes();
+ Class<?>[] parameterTypes = methods[j].getParameterTypes();
if (parameterTypes.length == 1 &&
List.class.isAssignableFrom(parameterTypes[0])) {
writeMethod = methods[j];
@@ -1110,7 +1111,7 @@
* @exception NoSuchMethodException if an accessor method for this
* propety cannot be found
*/
- public Class getPropertyEditorClass(Object bean, String name)
+ public Class<?> getPropertyEditorClass(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
@@ -1158,7 +1159,7 @@
* @exception NoSuchMethodException if an accessor method for this
* propety cannot be found
*/
- public Class getPropertyType(Object bean, String name)
+ public Class<?> getPropertyType(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
@@ -1193,7 +1194,7 @@
if (descriptor == null) {
return (null);
}
- Class type = descriptor.getType();
+ Class<?> type = descriptor.getType();
if (type == null) {
return (null);
} else if (type.isArray()) {
@@ -1246,7 +1247,7 @@
* @param descriptor Property descriptor to return a getter for
* @return The read method
*/
- Method getReadMethod(Class clazz, PropertyDescriptor descriptor) {
+ Method getReadMethod(Class<?> clazz, PropertyDescriptor descriptor) {
return (MethodUtils.getAccessibleMethod(clazz, descriptor.getReadMethod()));
}
@@ -1355,7 +1356,7 @@
* @param descriptor Property descriptor to return a setter for
* @return The write method
*/
- Method getWriteMethod(Class clazz, PropertyDescriptor descriptor) {
+ Method getWriteMethod(Class<?> clazz, PropertyDescriptor descriptor) {
return (MethodUtils.getAccessibleMethod(clazz, descriptor.getWriteMethod()));
}
@@ -1637,7 +1638,8 @@
Array.set(bean, index, value);
return;
} else if (bean instanceof List) {
- ((List)bean).set(index, value);
+ List<Object> list = toObjectList(bean);
+ list.set(index, value);
return;
}
}
@@ -1711,7 +1713,8 @@
if (!array.getClass().isArray()) {
if (array instanceof List) {
// Modify the specified value in the List
- ((List) array).set(index, value);
+ List<Object> list = toObjectList(array);
+ list.set(index, value);
} else {
throw new IllegalArgumentException("Property '" + name +
"' is not indexed on bean class '" + bean.getClass() + "'");
@@ -1864,7 +1867,8 @@
Object invokeResult = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY);
/* test and fetch from the map */
if (invokeResult instanceof java.util.Map) {
- ((java.util.Map)invokeResult).put(key, value);
+ java.util.Map<String, Object> map = toPropertyMap(invokeResult);
+ map.put(key, value);
}
} else {
throw new NoSuchMethodException("Property '" + name +
@@ -1924,7 +1928,7 @@
String next = resolver.next(name);
Object nestedBean = null;
if (bean instanceof Map) {
- nestedBean = getPropertyOfMapBean((Map)bean, next);
+ nestedBean = getPropertyOfMapBean((Map<?, ?>)bean, next);
} else if (resolver.isMapped(next)) {
nestedBean = getMappedProperty(bean, next);
} else if (resolver.isIndexed(next)) {
@@ -1942,7 +1946,7 @@
}
if (bean instanceof Map) {
- setPropertyOfMapBean((Map) bean, name, value);
+ setPropertyOfMapBean(toPropertyMap(bean), name, value);
} else if (resolver.isMapped(name)) {
setMappedProperty(bean, name, value);
} else if (resolver.isIndexed(name)) {
@@ -2009,7 +2013,7 @@
* no simple method is available.
* @since 1.8.0
*/
- protected void setPropertyOfMapBean(Map bean, String propertyName, Object value)
+ protected void setPropertyOfMapBean(Map<String, Object> bean, String propertyName, Object value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
@@ -2180,7 +2184,7 @@
}
}
String expectedString = "";
- Class[] parTypes = method.getParameterTypes();
+ Class<?>[] parTypes = method.getParameterTypes();
if (parTypes != null) {
for (int i = 0; i < parTypes.length; i++) {
if (i > 0) {
@@ -2217,7 +2221,7 @@
}
}
String expectedString = "";
- Class[] parTypes = method.getParameterTypes();
+ Class<?>[] parTypes = method.getParameterTypes();
if (parTypes != null) {
for (int i = 0; i < parTypes.length; i++) {
if (i > 0) {
@@ -2242,4 +2246,34 @@
}
}
+
+ /**
+ * Converts an object to a list of objects. This method is used when dealing
+ * with indexed properties. It assumes that indexed properties are stored as
+ * lists of objects.
+ *
+ * @param obj the object to be converted
+ * @return the resulting list of objects
+ */
+ private static List<Object> toObjectList(Object obj) {
+ @SuppressWarnings("unchecked")
+ // indexed properties are stored in lists of objects
+ List<Object> list = (List<Object>) obj;
+ return list;
+ }
+
+ /**
+ * Converts an object to a map with property values. This method is used
+ * when dealing with mapped properties. It assumes that mapped properties
+ * are stored in a Map<String, Object>.
+ *
+ * @param obj the object to be converted
+ * @return the resulting properties map
+ */
+ private static Map<String, Object> toPropertyMap(Object obj) {
+ @SuppressWarnings("unchecked")
+ // mapped properties are stores in maps of type <String, Object>
+ Map<String, Object> map = (Map<String, Object>) obj;
+ return map;
+ }
}
diff --git a/src/main/java/org/apache/commons/beanutils/ResultSetDynaClass.java b/src/main/java/org/apache/commons/beanutils/ResultSetDynaClass.java
index 21175db..8a68414 100644
--- a/src/main/java/org/apache/commons/beanutils/ResultSetDynaClass.java
+++ b/src/main/java/org/apache/commons/beanutils/ResultSetDynaClass.java
@@ -190,7 +190,7 @@
* should be called only once.</p>
* @return An <code>Iterator</code> of {@link DynaBean} instances
*/
- public Iterator iterator() {
+ public Iterator<DynaBean> iterator() {
return (new ResultSetIterator(this));
@@ -236,7 +236,7 @@
* @throws SQLException if the class cannot be loaded
*/
@Override
- protected Class loadClass(String className) throws SQLException {
+ protected Class<?> loadClass(String className) throws SQLException {
try {
return getClass().getClassLoader().loadClass(className);
diff --git a/src/main/java/org/apache/commons/beanutils/ResultSetIterator.java b/src/main/java/org/apache/commons/beanutils/ResultSetIterator.java
index 2a9528a..8efd0a0 100644
--- a/src/main/java/org/apache/commons/beanutils/ResultSetIterator.java
+++ b/src/main/java/org/apache/commons/beanutils/ResultSetIterator.java
@@ -33,7 +33,7 @@
* @version $Id$
*/
-public class ResultSetIterator implements DynaBean, Iterator {
+public class ResultSetIterator implements DynaBean, Iterator<DynaBean> {
// ------------------------------------------------------------ Constructor
@@ -301,7 +301,7 @@
*
* @return advance to the new row and return this
*/
- public Object next() {
+ public DynaBean next() {
try {
advance();
diff --git a/src/main/java/org/apache/commons/beanutils/RowSetDynaClass.java b/src/main/java/org/apache/commons/beanutils/RowSetDynaClass.java
index 2cc755e..2e6549a 100644
--- a/src/main/java/org/apache/commons/beanutils/RowSetDynaClass.java
+++ b/src/main/java/org/apache/commons/beanutils/RowSetDynaClass.java
@@ -82,7 +82,7 @@
* the original <code>ResultSet</code> on which this
* {@link RowSetDynaClass} was based.</p>
*/
- protected List rows = new ArrayList();
+ protected List<DynaBean> rows = new ArrayList<DynaBean>();
// ----------------------------------------------------------- Constructors
@@ -261,7 +261,7 @@
*
* @return A <code>List</code> of {@link DynaBean} instances
*/
- public List getRows() {
+ public List<DynaBean> getRows() {
return (this.rows);
diff --git a/src/main/java/org/apache/commons/beanutils/WeakFastHashMap.java b/src/main/java/org/apache/commons/beanutils/WeakFastHashMap.java
index 452665a..d5e5f68 100644
--- a/src/main/java/org/apache/commons/beanutils/WeakFastHashMap.java
+++ b/src/main/java/org/apache/commons/beanutils/WeakFastHashMap.java
@@ -61,12 +61,12 @@
* @since Commons Collections 1.0
* @version $Id$
*/
-class WeakFastHashMap extends HashMap {
+class WeakFastHashMap<K, V> extends HashMap<K, V> {
/**
* The underlying map we are managing.
*/
- private Map map = null;
+ private Map<K, V> map = null;
/**
* Are we currently operating in "fast" mode?
@@ -110,7 +110,7 @@
*
* @param map the map whose mappings are to be copied
*/
- public WeakFastHashMap(Map map) {
+ public WeakFastHashMap(Map<? extends K, ? extends V> map) {
super();
this.map = createMap(map);
}
@@ -153,7 +153,7 @@
* @return the value mapped to that key, or null
*/
@Override
- public Object get(Object key) {
+ public V get(Object key) {
if (fast) {
return (map.get(key));
} else {
@@ -247,11 +247,11 @@
* @return the value previously mapped to the key, or null
*/
@Override
- public Object put(Object key, Object value) {
+ public V put(K key, V value) {
if (fast) {
synchronized (this) {
- Map temp = cloneMap(map);
- Object result = temp.put(key, value);
+ Map<K, V> temp = cloneMap(map);
+ V result = temp.put(key, value);
map = temp;
return (result);
}
@@ -269,10 +269,10 @@
* @param in the map whose mappings are to be copied
*/
@Override
- public void putAll(Map in) {
+ public void putAll(Map<? extends K, ? extends V> in) {
if (fast) {
synchronized (this) {
- Map temp = cloneMap(map);
+ Map<K, V> temp = cloneMap(map);
temp.putAll(in);
map = temp;
}
@@ -291,11 +291,11 @@
* @return the value removed, or null
*/
@Override
- public Object remove(Object key) {
+ public V remove(Object key) {
if (fast) {
synchronized (this) {
- Map temp = cloneMap(map);
- Object result = temp.remove(key);
+ Map<K, V> temp = cloneMap(map);
+ V result = temp.remove(key);
map = temp;
return (result);
}
@@ -342,18 +342,16 @@
} else if (!(o instanceof Map)) {
return (false);
}
- Map mo = (Map) o;
+ Map<?, ?> mo = (Map<?, ?>) o;
// Compare the two maps for equality
if (fast) {
if (mo.size() != map.size()) {
return (false);
}
- Iterator i = map.entrySet().iterator();
- while (i.hasNext()) {
- Map.Entry e = (Map.Entry) i.next();
- Object key = e.getKey();
- Object value = e.getValue();
+ for (Map.Entry<K, V> e : map.entrySet()) {
+ K key = e.getKey();
+ V value = e.getValue();
if (value == null) {
if (!(mo.get(key) == null && mo.containsKey(key))) {
return (false);
@@ -371,11 +369,9 @@
if (mo.size() != map.size()) {
return (false);
}
- Iterator i = map.entrySet().iterator();
- while (i.hasNext()) {
- Map.Entry e = (Map.Entry) i.next();
- Object key = e.getKey();
- Object value = e.getValue();
+ for (Map.Entry<K, V> e : map.entrySet()) {
+ K key = e.getKey();
+ V value = e.getValue();
if (value == null) {
if (!(mo.get(key) == null && mo.containsKey(key))) {
return (false);
@@ -402,17 +398,15 @@
public int hashCode() {
if (fast) {
int h = 0;
- Iterator i = map.entrySet().iterator();
- while (i.hasNext()) {
- h += i.next().hashCode();
+ for (Map.Entry<K, V> e : map.entrySet()) {
+ h += e.hashCode();
}
return (h);
} else {
synchronized (map) {
int h = 0;
- Iterator i = map.entrySet().iterator();
- while (i.hasNext()) {
- h += i.next().hashCode();
+ for (Map.Entry<K, V> e : map.entrySet()) {
+ h += e.hashCode();
}
return (h);
}
@@ -427,12 +421,12 @@
*/
@Override
public Object clone() {
- WeakFastHashMap results = null;
+ WeakFastHashMap<K, V> results = null;
if (fast) {
- results = new WeakFastHashMap(map);
+ results = new WeakFastHashMap<K, V>(map);
} else {
synchronized (map) {
- results = new WeakFastHashMap(map);
+ results = new WeakFastHashMap<K, V>(map);
}
}
results.setFast(getFast());
@@ -448,7 +442,7 @@
* @return the set of map Map entries
*/
@Override
- public Set entrySet() {
+ public Set<Map.Entry<K, V>> entrySet() {
return new EntrySet();
}
@@ -457,7 +451,7 @@
* @return the set of the Map's keys
*/
@Override
- public Set keySet() {
+ public Set<K> keySet() {
return new KeySet();
}
@@ -466,30 +460,30 @@
* @return the set of the Map's values
*/
@Override
- public Collection values() {
+ public Collection<V> values() {
return new Values();
}
// Abstractions on Map creations (for subclasses such as WeakFastHashMap)
// ----------------------------------------------------------------------
- protected Map createMap() {
- return new WeakHashMap();
+ protected Map<K, V> createMap() {
+ return new WeakHashMap<K, V>();
}
- protected Map createMap(int capacity) {
- return new WeakHashMap(capacity);
+ protected Map<K, V> createMap(int capacity) {
+ return new WeakHashMap<K, V>(capacity);
}
- protected Map createMap(int capacity, float factor) {
- return new WeakHashMap(capacity, factor);
+ protected Map<K, V> createMap(int capacity, float factor) {
+ return new WeakHashMap<K, V>(capacity, factor);
}
- protected Map createMap(Map map) {
- return new WeakHashMap(map);
+ protected Map<K, V> createMap(Map<? extends K, ? extends V> map) {
+ return new WeakHashMap<K, V>(map);
}
- protected Map cloneMap(Map map) {
+ protected Map<K, V> cloneMap(Map<? extends K, ? extends V> map) {
return createMap(map);
}
@@ -498,14 +492,16 @@
/**
* Abstract collection implementation shared by keySet(), values() and entrySet().
+ *
+ * @param <E> the element type
*/
- private abstract class CollectionView implements Collection {
+ private abstract class CollectionView<E> implements Collection<E> {
public CollectionView() {
}
- protected abstract Collection get(Map map);
- protected abstract Object iteratorNext(Map.Entry entry);
+ protected abstract Collection<E> get(Map<K, V> map);
+ protected abstract E iteratorNext(Map.Entry<K, V> entry);
public void clear() {
@@ -523,7 +519,7 @@
public boolean remove(Object o) {
if (fast) {
synchronized (WeakFastHashMap.this) {
- Map temp = cloneMap(map);
+ Map<K, V> temp = cloneMap(map);
boolean r = get(temp).remove(o);
map = temp;
return r;
@@ -535,10 +531,10 @@
}
}
- public boolean removeAll(Collection o) {
+ public boolean removeAll(Collection<?> o) {
if (fast) {
synchronized (WeakFastHashMap.this) {
- Map temp = cloneMap(map);
+ Map<K, V> temp = cloneMap(map);
boolean r = get(temp).removeAll(o);
map = temp;
return r;
@@ -550,10 +546,10 @@
}
}
- public boolean retainAll(Collection o) {
+ public boolean retainAll(Collection<?> o) {
if (fast) {
synchronized (WeakFastHashMap.this) {
- Map temp = cloneMap(map);
+ Map<K, V> temp = cloneMap(map);
boolean r = get(temp).retainAll(o);
map = temp;
return r;
@@ -596,7 +592,7 @@
}
}
- public boolean containsAll(Collection o) {
+ public boolean containsAll(Collection<?> o) {
if (fast) {
return get(map).containsAll(o);
} else {
@@ -606,7 +602,7 @@
}
}
- public Object[] toArray(Object[] o) {
+ public <T> T[] toArray(T[] o) {
if (fast) {
return get(map).toArray(o);
} else {
@@ -652,23 +648,23 @@
}
}
- public boolean add(Object o) {
+ public boolean add(E o) {
throw new UnsupportedOperationException();
}
- public boolean addAll(Collection c) {
+ public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
- public Iterator iterator() {
+ public Iterator<E> iterator() {
return new CollectionViewIterator();
}
- private class CollectionViewIterator implements Iterator {
+ private class CollectionViewIterator implements Iterator<E> {
- private Map expected;
- private Map.Entry lastReturned = null;
- private final Iterator iterator;
+ private Map<K, V> expected;
+ private Map.Entry<K, V> lastReturned = null;
+ private final Iterator<Map.Entry<K, V>> iterator;
public CollectionViewIterator() {
this.expected = map;
@@ -682,11 +678,11 @@
return iterator.hasNext();
}
- public Object next() {
+ public E next() {
if (expected != map) {
throw new ConcurrentModificationException();
}
- lastReturned = (Map.Entry)iterator.next();
+ lastReturned = iterator.next();
return iteratorNext(lastReturned);
}
@@ -714,15 +710,15 @@
/**
* Set implementation over the keys of the FastHashMap
*/
- private class KeySet extends CollectionView implements Set {
+ private class KeySet extends CollectionView<K> implements Set<K> {
@Override
- protected Collection get(Map map) {
+ protected Collection<K> get(Map<K, V> map) {
return map.keySet();
}
@Override
- protected Object iteratorNext(Map.Entry entry) {
+ protected K iteratorNext(Map.Entry<K, V> entry) {
return entry.getKey();
}
@@ -731,15 +727,15 @@
/**
* Collection implementation over the values of the FastHashMap
*/
- private class Values extends CollectionView {
+ private class Values extends CollectionView<V> {
@Override
- protected Collection get(Map map) {
+ protected Collection<V> get(Map<K, V> map) {
return map.values();
}
@Override
- protected Object iteratorNext(Map.Entry entry) {
+ protected V iteratorNext(Map.Entry<K, V> entry) {
return entry.getValue();
}
}
@@ -747,15 +743,15 @@
/**
* Set implementation over the entries of the FastHashMap
*/
- private class EntrySet extends CollectionView implements Set {
+ private class EntrySet extends CollectionView<Map.Entry<K, V>> implements Set<Map.Entry<K, V>> {
@Override
- protected Collection get(Map map) {
+ protected Collection<Map.Entry<K, V>> get(Map<K, V> map) {
return map.entrySet();
}
@Override
- protected Object iteratorNext(Map.Entry entry) {
+ protected Map.Entry<K, V> iteratorNext(Map.Entry<K, V> entry) {
return entry;
}
diff --git a/src/main/java/org/apache/commons/beanutils/WrapDynaClass.java b/src/main/java/org/apache/commons/beanutils/WrapDynaClass.java
index 5a98185..624dfa5 100644
--- a/src/main/java/org/apache/commons/beanutils/WrapDynaClass.java
+++ b/src/main/java/org/apache/commons/beanutils/WrapDynaClass.java
@@ -60,9 +60,9 @@
*
* @param beanClass JavaBean class to be introspected around
*/
- private WrapDynaClass(Class beanClass) {
+ private WrapDynaClass(Class<?> beanClass) {
- this.beanClassRef = new SoftReference(beanClass);
+ this.beanClassRef = new SoftReference<Class<?>>(beanClass);
this.beanClassName = beanClass.getName();
introspect();
@@ -79,7 +79,7 @@
/**
* Reference to the JavaBean class represented by this WrapDynaClass.
*/
- private Reference beanClassRef = null;
+ private Reference<Class<?>> beanClassRef = null;
/**
* The JavaBean <code>Class</code> which is represented by this
@@ -88,7 +88,7 @@
* @deprecated No longer initialized, use getBeanClass() method instead
*/
@Deprecated
- protected Class beanClass = null;
+ protected Class<?> beanClass = null;
/**
@@ -102,7 +102,7 @@
* property name. Individual descriptor instances will be the same
* instances as those in the <code>descriptors</code> list.
*/
- protected HashMap descriptorsMap = new HashMap();
+ protected HashMap<String, PropertyDescriptor> descriptorsMap = new HashMap<String, PropertyDescriptor>();
/**
@@ -116,25 +116,25 @@
* keyed by the property name. Individual descriptor instances will
* be the same instances as those in the <code>properties</code> list.
*/
- protected HashMap propertiesMap = new HashMap();
+ protected HashMap<String, DynaProperty> propertiesMap = new HashMap<String, DynaProperty>();
// ------------------------------------------------------- Static Variables
- private static final ContextClassLoaderLocal CLASSLOADER_CACHE =
- new ContextClassLoaderLocal() {
+ private static final ContextClassLoaderLocal<Map<Object, Object>> CLASSLOADER_CACHE =
+ new ContextClassLoaderLocal<Map<Object, Object>>() {
@Override
- protected Object initialValue() {
- return new WeakHashMap();
+ protected Map<Object, Object> initialValue() {
+ return new WeakHashMap<Object, Object>();
}
};
/**
* Get the wrap dyna classes cache
*/
- private static Map getDynaClassesMap() {
- return (Map)CLASSLOADER_CACHE.get();
+ private static Map<Object, Object> getDynaClassesMap() {
+ return CLASSLOADER_CACHE.get();
}
/**
@@ -174,7 +174,7 @@
* @deprecated The dynaClasses Map will be removed in a subsequent release
*/
@Deprecated
- protected static HashMap dynaClasses = new HashMap() {
+ protected static HashMap<Object, Object> dynaClasses = new HashMap<Object, Object>() {
@Override
public void clear() {
getDynaClassesMap().clear();
@@ -188,7 +188,7 @@
return getDynaClassesMap().containsValue(value);
}
@Override
- public Set entrySet() {
+ public Set<Map.Entry<Object, Object>> entrySet() {
return getDynaClassesMap().entrySet();
}
@Override
@@ -208,7 +208,7 @@
return getDynaClassesMap().isEmpty();
}
@Override
- public Set keySet() {
+ public Set<Object> keySet() {
return getDynaClassesMap().keySet();
}
@Override
@@ -216,7 +216,7 @@
return getDynaClassesMap().put(key, value);
}
@Override
- public void putAll(Map m) {
+ public void putAll(Map<? extends Object, ? extends Object> m) {
getDynaClassesMap().putAll(m);
}
@Override
@@ -228,7 +228,7 @@
return getDynaClassesMap().size();
}
@Override
- public Collection values() {
+ public Collection<Object> values() {
return getDynaClassesMap().values();
}
};
@@ -242,8 +242,8 @@
* @return the class of the underlying wrapped bean
* @since 1.8.0
*/
- protected Class getBeanClass() {
- return (Class)beanClassRef.get();
+ protected Class<?> getBeanClass() {
+ return beanClassRef.get();
}
/**
@@ -277,7 +277,7 @@
throw new IllegalArgumentException
("No property name specified");
}
- return ((DynaProperty) propertiesMap.get(name));
+ return (propertiesMap.get(name));
}
@@ -345,7 +345,7 @@
*/
public PropertyDescriptor getPropertyDescriptor(String name) {
- return ((PropertyDescriptor) descriptorsMap.get(name));
+ return (descriptorsMap.get(name));
}
@@ -370,7 +370,7 @@
* @param beanClass Bean class for which a WrapDynaClass is requested
* @return A new <i>Wrap</i> {@link DynaClass}
*/
- public static WrapDynaClass createDynaClass(Class beanClass) {
+ public static WrapDynaClass createDynaClass(Class<?> beanClass) {
WrapDynaClass dynaClass =
(WrapDynaClass) getDynaClassesMap().get(beanClass);
@@ -392,16 +392,16 @@
protected void introspect() {
// Look up the property descriptors for this bean class
- Class beanClass = getBeanClass();
+ Class<?> beanClass = getBeanClass();
PropertyDescriptor[] regulars =
PropertyUtils.getPropertyDescriptors(beanClass);
if (regulars == null) {
regulars = new PropertyDescriptor[0];
}
- Map mappeds =
+ Map<?, ?> mappeds =
PropertyUtils.getMappedPropertyDescriptors(beanClass);
if (mappeds == null) {
- mappeds = new HashMap();
+ mappeds = new HashMap<Object, Object>();
}
// Construct corresponding DynaProperty information
@@ -416,7 +416,7 @@
properties[i]);
}
int j = regulars.length;
- Iterator names = mappeds.keySet().iterator();
+ Iterator<?> names = mappeds.keySet().iterator();
while (names.hasNext()) {
String name = (String) names.next();
PropertyDescriptor descriptor =
diff --git a/src/main/java/org/apache/commons/beanutils/converters/AbstractConverter.java b/src/main/java/org/apache/commons/beanutils/converters/AbstractConverter.java
index ba2623a..96e8341 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/AbstractConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/AbstractConverter.java
@@ -18,11 +18,13 @@
import java.lang.reflect.Array;
import java.util.Collection;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
+import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
/**
* Base {@link Converter} implementation that provides the structure
@@ -43,6 +45,12 @@
* <li><code>convertToType(Class, value)</code> - convert
* to the specified type</li>
* </ul>
+ * <p>
+ * The default value has to be compliant to the default type of this
+ * converter - which is enforced by the generic type parameter. If a
+ * conversion is not possible and a default value is set, the converter
+ * tries to transform the default value to the requested target type.
+ * If this fails, a {@code ConversionException} if thrown.
*
* @version $Id$
* @since 1.8.0
@@ -112,16 +120,21 @@
* Convert the input object into an output object of the
* specified type.
*
+ * @param <T> the target type of the conversion
* @param type Data type to which this value should be converted
* @param value The input value to be converted
* @return The converted value.
* @throws ConversionException if conversion cannot be performed
* successfully and no default is specified.
*/
- public Object convert(Class type, Object value) {
+ public <T> T convert(Class<T> type, Object value) {
- Class sourceType = value == null ? null : value.getClass();
- Class targetType = primitive(type == null ? getDefaultType() : type);
+ if (type == null) {
+ return convertToDefaultType(type, value);
+ }
+
+ Class<?> sourceType = value == null ? null : value.getClass();
+ Class<T> targetType = ConvertUtils.primitiveToWrapper(type);
if (log().isDebugEnabled()) {
log().debug("Converting"
@@ -141,7 +154,7 @@
try {
// Convert --> String
if (targetType.equals(String.class)) {
- return convertToString(value);
+ return targetType.cast(convertToString(value));
// No conversion necessary
} else if (targetType.equals(sourceType)) {
@@ -149,7 +162,7 @@
log().debug(" No conversion required, value is already a "
+ toString(targetType));
}
- return value;
+ return targetType.cast(value);
// Convert --> Type
} else {
@@ -158,7 +171,7 @@
log().debug(" Converted to " + toString(targetType) +
" value '" + result + "'");
}
- return result;
+ return targetType.cast(result);
}
} catch (Throwable t) {
return handleError(targetType, value, t);
@@ -194,7 +207,7 @@
* @return The converted value.
* @throws Throwable if an error occurs converting to the specified type
*/
- protected abstract Object convertToType(Class type, Object value) throws Throwable;
+ protected abstract <T> T convertToType(Class<T> type, Object value) throws Throwable;
/**
* Return the first element from an Array (or Collection)
@@ -218,7 +231,7 @@
}
}
if (value instanceof Collection) {
- Collection collection = (Collection)value;
+ Collection<?> collection = (Collection<?>)value;
if (collection.size() > 0) {
return collection.iterator().next();
} else {
@@ -241,7 +254,7 @@
* @throws ConversionException if no default value has been
* specified for this {@link Converter}.
*/
- protected Object handleError(Class type, Object value, Throwable cause) {
+ protected <T> T handleError(Class<T> type, Object value, Throwable cause) {
if (log().isDebugEnabled()) {
if (cause instanceof ConversionException) {
log().debug(" Conversion threw ConversionException: " + cause.getMessage());
@@ -279,15 +292,16 @@
/**
* Handle missing values.
* <p>
- * If a default value has been specified then it is returned
- * otherwise a ConversionException is thrown.
+ * If a default value has been specified, then it is returned (after a cast
+ * to the desired target class); otherwise a ConversionException is thrown.
*
+ * @param <T> the desired target type
* @param type Data type to which this value should be converted.
* @return The default value.
* @throws ConversionException if no default value has been
* specified for this {@link Converter}.
*/
- protected Object handleMissing(Class type) {
+ protected <T> T handleMissing(Class<T> type) {
if (useDefault || type.equals(String.class)) {
Object value = getDefault(type);
@@ -295,8 +309,8 @@
try {
value = convertToType(type, defaultValue);
} catch (Throwable t) {
- log().error(" Default conversion to " + toString(type)
- + "failed: " + t);
+ throw new ConversionException("Default conversion to " + toString(type)
+ + " failed.", t);
}
}
if (log().isDebugEnabled()) {
@@ -304,7 +318,8 @@
+ (value == null ? "" : toString(value.getClass()) + " ")
+ "value '" + defaultValue + "'");
}
- return value;
+ // value is now either null or of the desired target type
+ return type.cast(value);
}
ConversionException cex = new ConversionException("No value specified for '" +
@@ -348,7 +363,7 @@
*
* @return The default type this <code>Converter</code> handles.
*/
- protected abstract Class getDefaultType();
+ protected abstract Class<?> getDefaultType();
/**
* Return the default value for conversions to the specified
@@ -356,10 +371,10 @@
* @param type Data type to which this value should be converted.
* @return The default value for the specified type.
*/
- protected Object getDefault(Class type) {
+ protected Object getDefault(Class<?> type) {
if (type.equals(String.class)) {
return null;
- } else {
+ } else {
return defaultValue;
}
}
@@ -394,47 +409,16 @@
}
/**
- * Change primitve Class types to the associated wrapper class.
- * @param type The class type to check.
- * @return The converted type.
- */
- Class primitive(Class type) {
- if (type == null || !type.isPrimitive()) {
- return type;
- }
-
- if (type == Integer.TYPE) {
- return Integer.class;
- } else if (type == Double.TYPE) {
- return Double.class;
- } else if (type == Long.TYPE) {
- return Long.class;
- } else if (type == Boolean.TYPE) {
- return Boolean.class;
- } else if (type == Float.TYPE) {
- return Float.class;
- } else if (type == Short.TYPE) {
- return Short.class;
- } else if (type == Byte.TYPE) {
- return Byte.class;
- } else if (type == Character.TYPE) {
- return Character.class;
- } else {
- return type;
- }
- }
-
- /**
* Provide a String representation of a <code>java.lang.Class</code>.
* @param type The <code>java.lang.Class</code>.
* @return The String representation.
*/
- String toString(Class type) {
+ String toString(Class<?> type) {
String typeName = null;
if (type == null) {
typeName = "null";
} else if (type.isArray()) {
- Class elementType = type.getComponentType();
+ Class<?> elementType = type.getComponentType();
int count = 1;
while (elementType.isArray()) {
elementType = elementType .getComponentType();
@@ -456,4 +440,35 @@
}
return typeName;
}
+
+ /**
+ * Performs a conversion to the default type. This method is called if we do
+ * not have a target class. In this case, the T parameter is not set.
+ * Therefore, we can cast to it (which is required to fulfill the contract
+ * of the method signature).
+ *
+ * @param <T> the type of the result object
+ * @param targetClass the target class of the conversion
+ * @param value the value to be converted
+ * @return the converted value
+ */
+ private <T> T convertToDefaultType(Class<T> targetClass, Object value) {
+ @SuppressWarnings("unchecked")
+ T result = (T) convert(getDefaultType(), value);
+ return result;
+ }
+
+ /**
+ * Generates a standard conversion exception with a message indicating that
+ * the passed in value cannot be converted to the desired target type.
+ *
+ * @param type the target type
+ * @param value the value to be converted
+ * @return a {@code ConversionException} with a standard message
+ * @since 1.9
+ */
+ protected ConversionException conversionException(Class<?> type, Object value) {
+ return new ConversionException("Can't convert value '" + value
+ + "' to type " + type);
+ }
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/ArrayConverter.java b/src/main/java/org/apache/commons/beanutils/converters/ArrayConverter.java
index ee6b392..49d6886 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/ArrayConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/ArrayConverter.java
@@ -16,15 +16,16 @@
*/
package org.apache.commons.beanutils.converters;
-import java.util.Collections;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Collection;
+import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
-import java.io.IOException;
import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
@@ -53,7 +54,7 @@
* or by converting the first element in the array to a String - this
* is controlled by the {@link ArrayConverter#setOnlyFirstToString(boolean)}
* parameter.</li>
- * <li><b>Multi Dimensional Arrays</b> - its possible to convert a <code>String</code>
+ * <li><b>Multi Dimensional Arrays</b> - it is possible to convert a <code>String</code>
* to a multi-dimensional arrays, by embedding {@link ArrayConverter}
* within each other - see example below.</li>
* <li><b>Default Value</b></li>
@@ -121,12 +122,13 @@
* int[][] result = (int[][])matrixConverter.convert(int[][].class, matrixString);
* </pre>
*
+ * @param <D> the default type of this array converter
* @version $Id$
* @since 1.8.0
*/
public class ArrayConverter extends AbstractConverter {
- private final Object defaultTypeInstance;
+ private final Class<?> defaultType;
private final Converter elementConverter;
private int defaultSize;
private char delimiter = ',';
@@ -145,7 +147,7 @@
* @param elementConverter Converter used to convert
* individual array elements.
*/
- public ArrayConverter(Class defaultType, Converter elementConverter) {
+ public ArrayConverter(Class<?> defaultType, Converter elementConverter) {
super();
if (defaultType == null) {
throw new IllegalArgumentException("Default type is missing");
@@ -156,7 +158,7 @@
if (elementConverter == null) {
throw new IllegalArgumentException("Component Converter is missing.");
}
- this.defaultTypeInstance = Array.newInstance(defaultType.getComponentType(), 0);
+ this.defaultType = defaultType;
this.elementConverter = elementConverter;
}
@@ -172,7 +174,7 @@
* @param defaultSize Specifies the size of the default array value or if less
* than zero indicates that a <code>null</code> default value should be used.
*/
- public ArrayConverter(Class defaultType, Converter elementConverter, int defaultSize) {
+ public ArrayConverter(Class<?> defaultType, Converter elementConverter, int defaultSize) {
this(defaultType, elementConverter);
this.defaultSize = defaultSize;
Object defaultValue = null;
@@ -220,8 +222,8 @@
* @return The default type this <code>Converter</code> handles.
*/
@Override
- protected Class getDefaultType() {
- return defaultTypeInstance.getClass();
+ protected Class<?> getDefaultType() {
+ return defaultType;
}
/**
@@ -235,12 +237,12 @@
protected String convertToString(Object value) throws Throwable {
int size = 0;
- Iterator iterator = null;
- Class type = value.getClass();
+ Iterator<?> iterator = null;
+ Class<?> type = value.getClass();
if (type.isArray()) {
size = Array.getLength(value);
} else {
- Collection collection = convertToCollection(type, value);
+ Collection<?> collection = convertToCollection(type, value);
size = collection.size();
iterator = collection.iterator();
}
@@ -254,7 +256,7 @@
}
// Create a StringBuffer containing a delimited list of the values
- StringBuffer buffer = new StringBuffer();
+ StringBuilder buffer = new StringBuilder();
for (int i = 0; i < size; i++) {
if (i > 0) {
buffer.append(delimiter);
@@ -279,7 +281,7 @@
* @throws Throwable if an error occurs converting to the specified type
*/
@Override
- protected Object convertToType(Class type, Object value) throws Throwable {
+ protected <T> T convertToType(Class<T> type, Object value) throws Throwable {
if (!type.isArray()) {
throw new ConversionException(toString(getClass())
@@ -289,17 +291,17 @@
// Handle the source
int size = 0;
- Iterator iterator = null;
+ Iterator<?> iterator = null;
if (value.getClass().isArray()) {
size = Array.getLength(value);
} else {
- Collection collection = convertToCollection(type, value);
+ Collection<?> collection = convertToCollection(type, value);
size = collection.size();
iterator = collection.iterator();
}
// Allocate a new Array
- Class componentType = type.getComponentType();
+ Class<?> componentType = type.getComponentType();
Object newArray = Array.newInstance(componentType, size);
// Convert and set each element in the new Array
@@ -311,7 +313,11 @@
Array.set(newArray, i, element);
}
- return newArray;
+ @SuppressWarnings("unchecked")
+ // This is safe because T is an array type and newArray is an array of
+ // T's component type
+ T result = (T) newArray;
+ return result;
}
/**
@@ -346,14 +352,14 @@
* @param value value to be converted
* @return Collection elements.
*/
- protected Collection convertToCollection(Class type, Object value) {
+ protected Collection<?> convertToCollection(Class<?> type, Object value) {
if (value instanceof Collection) {
- return (Collection)value;
+ return (Collection<?>)value;
}
if (value instanceof Number ||
value instanceof Boolean ||
value instanceof java.util.Date) {
- List list = new ArrayList(1);
+ List<Object> list = new ArrayList<Object>(1);
list.add(value);
return list;
}
@@ -368,7 +374,7 @@
* @return The default value for the specified type.
*/
@Override
- protected Object getDefault(Class type) {
+ protected Object getDefault(Class<?> type) {
if (type.equals(String.class)) {
return null;
}
@@ -393,7 +399,7 @@
*/
@Override
public String toString() {
- StringBuffer buffer = new StringBuffer();
+ StringBuilder buffer = new StringBuilder();
buffer.append(toString(getClass()));
buffer.append("[UseDefault=");
buffer.append(isUseDefault());
@@ -425,7 +431,7 @@
* @throws NullPointerException if <code>svalue</code>
* is <code>null</code>
*/
- private List parseElements(Class type, String value) {
+ private List<String> parseElements(Class<?> type, String value) {
if (log().isDebugEnabled()) {
log().debug("Parsing elements, delimiter=[" + delimiter + "], value=[" + value + "]");
@@ -450,13 +456,13 @@
}
// Split comma-delimited tokens into a List
- List list = null;
+ List<String> list = null;
while (true) {
int ttype = st.nextToken();
if ((ttype == StreamTokenizer.TT_WORD) || (ttype > 0)) {
if (st.sval != null) {
if (list == null) {
- list = new ArrayList();
+ list = new ArrayList<String>();
}
list.add(st.sval);
}
@@ -469,7 +475,7 @@
}
if (list == null) {
- list = Collections.EMPTY_LIST;
+ list = Collections.emptyList();
}
if (log().isDebugEnabled()) {
log().debug(list.size() + " elements parsed");
diff --git a/src/main/java/org/apache/commons/beanutils/converters/BigDecimalConverter.java b/src/main/java/org/apache/commons/beanutils/converters/BigDecimalConverter.java
index afaf7d3..fb1a140 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/BigDecimalConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/BigDecimalConverter.java
@@ -62,7 +62,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<BigDecimal> getDefaultType() {
return BigDecimal.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/BigIntegerConverter.java b/src/main/java/org/apache/commons/beanutils/converters/BigIntegerConverter.java
index f44012f..b7a755c 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/BigIntegerConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/BigIntegerConverter.java
@@ -62,7 +62,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<BigInteger> getDefaultType() {
return BigInteger.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/BooleanConverter.java b/src/main/java/org/apache/commons/beanutils/converters/BooleanConverter.java
index c925945..953da45 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/BooleanConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/BooleanConverter.java
@@ -178,7 +178,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<Boolean> getDefaultType() {
return Boolean.class;
}
@@ -202,27 +202,29 @@
* @since 1.8.0
*/
@Override
- protected Object convertToType(Class type, Object value) throws Throwable {
+ protected <T> T convertToType(Class<T> type, Object value) throws Throwable {
- // All the values in the trueStrings and falseStrings arrays are
- // guaranteed to be lower-case. By converting the input value
- // to lowercase too, we can use the efficient String.equals method
- // instead of the less-efficient String.equalsIgnoreCase method.
- String stringValue = value.toString().toLowerCase();
+ if (Boolean.class.equals(type) || Boolean.TYPE.equals(type)) {
+ // All the values in the trueStrings and falseStrings arrays are
+ // guaranteed to be lower-case. By converting the input value
+ // to lowercase too, we can use the efficient String.equals method
+ // instead of the less-efficient String.equalsIgnoreCase method.
+ String stringValue = value.toString().toLowerCase();
- for(int i=0; i<trueStrings.length; ++i) {
- if (trueStrings[i].equals(stringValue)) {
- return Boolean.TRUE;
+ for (int i = 0; i < trueStrings.length; ++i) {
+ if (trueStrings[i].equals(stringValue)) {
+ return type.cast(Boolean.TRUE);
+ }
+ }
+
+ for (int i = 0; i < falseStrings.length; ++i) {
+ if (falseStrings[i].equals(stringValue)) {
+ return type.cast(Boolean.FALSE);
+ }
}
}
- for(int i=0; i<falseStrings.length; ++i) {
- if (falseStrings[i].equals(stringValue)) {
- return Boolean.FALSE;
- }
- }
-
- throw new ConversionException("Can't convert value '" + value + "' to a Boolean");
+ throw conversionException(type, value);
}
/**
diff --git a/src/main/java/org/apache/commons/beanutils/converters/ByteConverter.java b/src/main/java/org/apache/commons/beanutils/converters/ByteConverter.java
index 5d87fe4..d35a121 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/ByteConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/ByteConverter.java
@@ -60,7 +60,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<Byte> getDefaultType() {
return Byte.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/CalendarConverter.java b/src/main/java/org/apache/commons/beanutils/converters/CalendarConverter.java
index 695bc76..66d00d3 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/CalendarConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/CalendarConverter.java
@@ -61,7 +61,7 @@
* @return The default type this <code>Converter</code> handles.
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return Calendar.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/CharacterConverter.java b/src/main/java/org/apache/commons/beanutils/converters/CharacterConverter.java
index 87d0465..0592389 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/CharacterConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/CharacterConverter.java
@@ -16,6 +16,7 @@
*/
package org.apache.commons.beanutils.converters;
+
/**
* {@link org.apache.commons.beanutils.Converter} implementaion that handles conversion
* to and from <b>java.lang.Character</b> objects.
@@ -55,7 +56,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return Character.class;
}
@@ -82,8 +83,12 @@
* @since 1.8.0
*/
@Override
- protected Object convertToType(Class type, Object value) throws Exception {
- return new Character(value.toString().charAt(0));
+ protected <T> T convertToType(Class<T> type, Object value) throws Exception {
+ if (Character.class.equals(type) || Character.TYPE.equals(type)) {
+ return type.cast(new Character(value.toString().charAt(0)));
+ }
+
+ throw conversionException(type, value);
}
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/ClassConverter.java b/src/main/java/org/apache/commons/beanutils/converters/ClassConverter.java
index 705c775..c82507d 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/ClassConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/ClassConverter.java
@@ -59,7 +59,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return Class.class;
}
@@ -72,7 +72,7 @@
*/
@Override
protected String convertToString(Object value) {
- return (value instanceof Class) ? ((Class)value).getName() : value.toString();
+ return (value instanceof Class) ? ((Class<?>)value).getName() : value.toString();
}
/**
@@ -85,21 +85,25 @@
* @since 1.8.0
*/
@Override
- protected Object convertToType(Class type, Object value) throws Throwable {
- ClassLoader classLoader =
- Thread.currentThread().getContextClassLoader();
- if (classLoader != null) {
- try {
- return (classLoader.loadClass(value.toString()));
- } catch (ClassNotFoundException ex) {
- // Don't fail, carry on and try this class's class loader
- // (see issue# BEANUTILS-263)
+ protected <T> T convertToType(Class<T> type, Object value) throws Throwable {
+ if (Class.class.equals(type)) {
+ ClassLoader classLoader = Thread.currentThread()
+ .getContextClassLoader();
+ if (classLoader != null) {
+ try {
+ return type.cast(classLoader.loadClass(value.toString()));
+ } catch (ClassNotFoundException ex) {
+ // Don't fail, carry on and try this class's class loader
+ // (see issue# BEANUTILS-263)
+ }
}
+
+ // Try this class's class loader
+ classLoader = ClassConverter.class.getClassLoader();
+ return type.cast(classLoader.loadClass(value.toString()));
}
- // Try this class's class loader
- classLoader = ClassConverter.class.getClassLoader();
- return (classLoader.loadClass(value.toString()));
+ throw conversionException(type, value);
}
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/ConverterFacade.java b/src/main/java/org/apache/commons/beanutils/converters/ConverterFacade.java
index e2c8de3..695349a 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/ConverterFacade.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/ConverterFacade.java
@@ -52,11 +52,12 @@
* specified type by delegating to the underlying {@link Converter}
* implementation.
*
+ * @param <T> The result type of the conversion
* @param type Data type to which this value should be converted
* @param value The input value to be converted
* @return The converted value.
*/
- public Object convert(Class type, Object value) {
+ public <T> T convert(Class<T> type, Object value) {
return converter.convert(type, value);
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/DateConverter.java b/src/main/java/org/apache/commons/beanutils/converters/DateConverter.java
index 03a3665..c4cfbdc 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/DateConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/DateConverter.java
@@ -61,7 +61,7 @@
* @return The default type this <code>Converter</code> handles.
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return Date.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/DateTimeConverter.java b/src/main/java/org/apache/commons/beanutils/converters/DateTimeConverter.java
index 144cf86..d19d03f 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/DateTimeConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/DateTimeConverter.java
@@ -16,13 +16,14 @@
*/
package org.apache.commons.beanutils.converters;
+import java.text.DateFormat;
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
-import java.util.Calendar;
import java.util.TimeZone;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.text.ParsePosition;
+
import org.apache.commons.beanutils.ConversionException;
/**
@@ -277,15 +278,16 @@
* Otherwise the default <code>DateFormat</code> for the default locale
* (and <i>style</i> if configured) will be used.
*
+ * @param <T> The desired target type of the conversion.
* @param targetType Data type to which this value should be converted.
* @param value The input value to be converted.
* @return The converted value.
* @throws Exception if conversion cannot be performed successfully
*/
@Override
- protected Object convertToType(Class targetType, Object value) throws Exception {
+ protected <T> T convertToType(Class<T> targetType, Object value) throws Exception {
- Class sourceType = value.getClass();
+ Class<?> sourceType = value.getClass();
// Handle java.sql.Timestamp
if (value instanceof java.sql.Timestamp) {
@@ -335,7 +337,7 @@
calendar = parse(sourceType, targetType, stringValue, format);
}
if (Calendar.class.isAssignableFrom(targetType)) {
- return calendar;
+ return targetType.cast(calendar);
} else {
return toDate(targetType, calendar.getTime().getTime());
}
@@ -360,30 +362,31 @@
* <li><code>java.sql.Timestamp</code></li>
* </ul>
*
+ * @param <T> The target type
* @param type The Date type to convert to
* @param value The long value to convert.
* @return The converted date value.
*/
- private Object toDate(Class type, long value) {
+ private <T> T toDate(Class<T> type, long value) {
// java.util.Date
if (type.equals(Date.class)) {
- return new Date(value);
+ return type.cast(new Date(value));
}
// java.sql.Date
if (type.equals(java.sql.Date.class)) {
- return new java.sql.Date(value);
+ return type.cast(new java.sql.Date(value));
}
// java.sql.Time
if (type.equals(java.sql.Time.class)) {
- return new java.sql.Time(value);
+ return type.cast(new java.sql.Time(value));
}
// java.sql.Timestamp
if (type.equals(java.sql.Timestamp.class)) {
- return new java.sql.Timestamp(value);
+ return type.cast(new java.sql.Timestamp(value));
}
// java.util.Calendar
@@ -400,7 +403,7 @@
}
calendar.setTime(new Date(value));
calendar.setLenient(false);
- return calendar;
+ return type.cast(calendar);
}
String msg = toString(getClass()) + " cannot handle conversion to '"
@@ -425,15 +428,16 @@
* mechanism is provided for <code>java.util.Date</code>
* and <code>java.util.Calendar</code> type.
*
- * @param type The Number type to convert to
+ * @param <T> The target type
+ * @param type The date type to convert to
* @param value The String value to convert.
* @return The converted Number value.
*/
- private Object toDate(Class type, String value) {
+ private <T> T toDate(Class<T> type, String value) {
// java.sql.Date
if (type.equals(java.sql.Date.class)) {
try {
- return java.sql.Date.valueOf(value);
+ return type.cast(java.sql.Date.valueOf(value));
} catch (IllegalArgumentException e) {
throw new ConversionException(
"String must be in JDBC format [yyyy-MM-dd] to create a java.sql.Date");
@@ -443,7 +447,7 @@
// java.sql.Time
if (type.equals(java.sql.Time.class)) {
try {
- return java.sql.Time.valueOf(value);
+ return type.cast(java.sql.Time.valueOf(value));
} catch (IllegalArgumentException e) {
throw new ConversionException(
"String must be in JDBC format [HH:mm:ss] to create a java.sql.Time");
@@ -453,7 +457,7 @@
// java.sql.Timestamp
if (type.equals(java.sql.Timestamp.class)) {
try {
- return java.sql.Timestamp.valueOf(value);
+ return type.cast(java.sql.Timestamp.valueOf(value));
} catch (IllegalArgumentException e) {
throw new ConversionException(
"String must be in JDBC format [yyyy-MM-dd HH:mm:ss.fffffffff] " +
@@ -514,7 +518,7 @@
* @return The converted Date object.
* @throws Exception if an error occurs parsing the date.
*/
- private Calendar parse(Class sourceType, Class targetType, String value) throws Exception {
+ private Calendar parse(Class<?> sourceType, Class<?> targetType, String value) throws Exception {
Exception firstEx = null;
for (int i = 0; i < patterns.length; i++) {
try {
@@ -547,7 +551,7 @@
* @return The converted Calendar object.
* @throws ConversionException if the String cannot be converted.
*/
- private Calendar parse(Class sourceType, Class targetType, String value, DateFormat format) {
+ private Calendar parse(Class<?> sourceType, Class<?> targetType, String value, DateFormat format) {
logFormat("Parsing", format);
format.setLenient(false);
ParsePosition pos = new ParsePosition(0);
diff --git a/src/main/java/org/apache/commons/beanutils/converters/DoubleConverter.java b/src/main/java/org/apache/commons/beanutils/converters/DoubleConverter.java
index b5a83c3..70babb2 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/DoubleConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/DoubleConverter.java
@@ -60,7 +60,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<Double> getDefaultType() {
return Double.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/FileConverter.java b/src/main/java/org/apache/commons/beanutils/converters/FileConverter.java
index f718f28..1316de0 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/FileConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/FileConverter.java
@@ -57,13 +57,14 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return File.class;
}
/**
* <p>Convert the input object into a java.io.File.</p>
*
+ * @param <T> The target type of the conversion.
* @param type Data type to which this value should be converted.
* @param value The input value to be converted.
* @return The converted value.
@@ -71,7 +72,11 @@
* @since 1.8.0
*/
@Override
- protected Object convertToType(Class type, Object value) throws Throwable {
- return new File(value.toString());
+ protected <T> T convertToType(Class<T> type, Object value) throws Throwable {
+ if (File.class.equals(type)) {
+ return type.cast(new File(value.toString()));
+ }
+
+ throw conversionException(type, value);
}
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/FloatConverter.java b/src/main/java/org/apache/commons/beanutils/converters/FloatConverter.java
index 8ff13d4..865dc4f 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/FloatConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/FloatConverter.java
@@ -60,7 +60,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<Float> getDefaultType() {
return Float.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/IntegerConverter.java b/src/main/java/org/apache/commons/beanutils/converters/IntegerConverter.java
index acd0c68..b831896 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/IntegerConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/IntegerConverter.java
@@ -60,7 +60,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<Integer> getDefaultType() {
return Integer.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/LongConverter.java b/src/main/java/org/apache/commons/beanutils/converters/LongConverter.java
index 6064878..3fcb8b4 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/LongConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/LongConverter.java
@@ -60,7 +60,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<Long> getDefaultType() {
return Long.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/NumberConverter.java b/src/main/java/org/apache/commons/beanutils/converters/NumberConverter.java
index 43f22d7..53a7ce6 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/NumberConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/NumberConverter.java
@@ -16,15 +16,15 @@
*/
package org.apache.commons.beanutils.converters;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.text.NumberFormat;
+import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.text.NumberFormat;
-import java.text.DecimalFormat;
-import java.text.DecimalFormatSymbols;
-import java.text.ParsePosition;
import org.apache.commons.beanutils.ConversionException;
@@ -229,9 +229,9 @@
* @throws Throwable if an error occurs converting to the specified type
*/
@Override
- protected Object convertToType(Class targetType, Object value) throws Throwable {
+ protected <T> T convertToType(Class<T> targetType, Object value) throws Throwable {
- Class sourceType = value.getClass();
+ Class<?> sourceType = value.getClass();
// Handle Number
if (value instanceof Number) {
return toNumber(sourceType, targetType, (Number)value);
@@ -244,12 +244,12 @@
// Handle Date --> Long
if (value instanceof Date && Long.class.equals(targetType)) {
- return new Long(((Date)value).getTime());
+ return targetType.cast(new Long(((Date)value).getTime()));
}
// Handle Calendar --> Long
if (value instanceof Calendar && Long.class.equals(targetType)) {
- return new Long(((Calendar)value).getTime().getTime());
+ return targetType.cast(new Long(((Calendar)value).getTime().getTime()));
}
// Convert all other types to String & handle
@@ -296,11 +296,11 @@
*
* @return The converted value.
*/
- private Number toNumber(Class sourceType, Class targetType, Number value) {
+ private <T> T toNumber(Class<?> sourceType, Class<T> targetType, Number value) {
// Correct Number type already
if (targetType.equals(value.getClass())) {
- return value;
+ return targetType.cast(value);
}
// Byte
@@ -314,7 +314,7 @@
throw new ConversionException(toString(sourceType) + " value '" + value
+ "' is too small " + toString(targetType));
}
- return new Byte(value.byteValue());
+ return targetType.cast(new Byte(value.byteValue()));
}
// Short
@@ -328,7 +328,7 @@
throw new ConversionException(toString(sourceType) + " value '" + value
+ "' is too small " + toString(targetType));
}
- return new Short(value.shortValue());
+ return targetType.cast(new Short(value.shortValue()));
}
// Integer
@@ -342,12 +342,12 @@
throw new ConversionException(toString(sourceType) + " value '" + value
+ "' is too small " + toString(targetType));
}
- return new Integer(value.intValue());
+ return targetType.cast(new Integer(value.intValue()));
}
// Long
if (targetType.equals(Long.class)) {
- return new Long(value.longValue());
+ return targetType.cast(new Long(value.longValue()));
}
// Float
@@ -356,31 +356,31 @@
throw new ConversionException(toString(sourceType) + " value '" + value
+ "' is too large for " + toString(targetType));
}
- return new Float(value.floatValue());
+ return targetType.cast(new Float(value.floatValue()));
}
// Double
if (targetType.equals(Double.class)) {
- return new Double(value.doubleValue());
+ return targetType.cast(new Double(value.doubleValue()));
}
// BigDecimal
if (targetType.equals(BigDecimal.class)) {
if (value instanceof Float || value instanceof Double) {
- return new BigDecimal(value.toString());
+ return targetType.cast(new BigDecimal(value.toString()));
} else if (value instanceof BigInteger) {
- return new BigDecimal((BigInteger)value);
+ return targetType.cast(new BigDecimal((BigInteger)value));
} else {
- return BigDecimal.valueOf(value.longValue());
+ return targetType.cast(BigDecimal.valueOf(value.longValue()));
}
}
// BigInteger
if (targetType.equals(BigInteger.class)) {
if (value instanceof BigDecimal) {
- return ((BigDecimal)value).toBigInteger();
+ return targetType.cast(((BigDecimal)value).toBigInteger());
} else {
- return BigInteger.valueOf(value.longValue());
+ return targetType.cast(BigInteger.valueOf(value.longValue()));
}
}
@@ -413,7 +413,7 @@
*
* @return The converted Number value.
*/
- private Number toNumber(Class sourceType, Class targetType, String value) {
+ private Number toNumber(Class<?> sourceType, Class<?> targetType, String value) {
// Byte
if (targetType.equals(Byte.class)) {
@@ -530,7 +530,7 @@
/**
* Convert a String into a <code>Number</code> object.
- * @param sourceType TODO
+ * @param sourceType the source type of the conversion
* @param targetType The type to convert the value to
* @param value The String date value.
* @param format The NumberFormat to parse the String value.
@@ -538,7 +538,7 @@
* @return The converted Number object.
* @throws ConversionException if the String cannot be converted.
*/
- private Number parse(Class sourceType, Class targetType, String value, NumberFormat format) {
+ private Number parse(Class<?> sourceType, Class<?> targetType, String value, NumberFormat format) {
ParsePosition pos = new ParsePosition(0);
Number parsedNumber = format.parse(value, pos);
if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedNumber == null) {
diff --git a/src/main/java/org/apache/commons/beanutils/converters/ShortConverter.java b/src/main/java/org/apache/commons/beanutils/converters/ShortConverter.java
index 3412c16..084b6ef 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/ShortConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/ShortConverter.java
@@ -60,7 +60,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<Short> getDefaultType() {
return Short.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/SqlDateConverter.java b/src/main/java/org/apache/commons/beanutils/converters/SqlDateConverter.java
index 03732b3..1e98ee3 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/SqlDateConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/SqlDateConverter.java
@@ -62,7 +62,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return Date.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/SqlTimeConverter.java b/src/main/java/org/apache/commons/beanutils/converters/SqlTimeConverter.java
index bcef70d..2fb7810 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/SqlTimeConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/SqlTimeConverter.java
@@ -65,7 +65,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return Time.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/SqlTimestampConverter.java b/src/main/java/org/apache/commons/beanutils/converters/SqlTimestampConverter.java
index d84a469..c126dd1 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/SqlTimestampConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/SqlTimestampConverter.java
@@ -65,7 +65,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return Timestamp.class;
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/StringConverter.java b/src/main/java/org/apache/commons/beanutils/converters/StringConverter.java
index 46d7c4d..396474f 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/StringConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/StringConverter.java
@@ -71,7 +71,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return String.class;
}
@@ -86,8 +86,13 @@
* @since 1.8.0
*/
@Override
- protected Object convertToType(Class type, Object value) throws Throwable {
- return value.toString();
+ protected <T> T convertToType(Class<T> type, Object value) throws Throwable {
+ // We have to support Object, too, because this class is sometimes
+ // used for a standard to Object conversion
+ if (String.class.equals(type) || Object.class.equals(type)) {
+ return type.cast(value.toString());
+ }
+ throw conversionException(type, value);
}
diff --git a/src/main/java/org/apache/commons/beanutils/converters/URLConverter.java b/src/main/java/org/apache/commons/beanutils/converters/URLConverter.java
index 83d9f56..5b711b6 100644
--- a/src/main/java/org/apache/commons/beanutils/converters/URLConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/converters/URLConverter.java
@@ -57,7 +57,7 @@
* @since 1.8.0
*/
@Override
- protected Class getDefaultType() {
+ protected Class<?> getDefaultType() {
return URL.class;
}
@@ -71,8 +71,12 @@
* @since 1.8.0
*/
@Override
- protected Object convertToType(Class type, Object value) throws Throwable {
- return new URL(value.toString());
+ protected <T> T convertToType(Class<T> type, Object value) throws Throwable {
+ if (URL.class.equals(type)) {
+ return type.cast(new URL(value.toString()));
+ }
+
+ throw conversionException(type, value);
}
}
diff --git a/src/main/java/org/apache/commons/beanutils/locale/BaseLocaleConverter.java b/src/main/java/org/apache/commons/beanutils/locale/BaseLocaleConverter.java
index c2f518a..f650efd 100644
--- a/src/main/java/org/apache/commons/beanutils/locale/BaseLocaleConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/locale/BaseLocaleConverter.java
@@ -17,13 +17,14 @@
package org.apache.commons.beanutils.locale;
-import org.apache.commons.beanutils.ConversionException;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
import java.text.ParseException;
import java.util.Locale;
+import org.apache.commons.beanutils.ConversionException;
+import org.apache.commons.beanutils.ConvertUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
/**
* <p>The base class for all standart type locale-sensitive converters.
@@ -158,7 +159,7 @@
/**
* Convert the specified locale-sensitive input object into an output object.
- * The default pattern is used for the convertion.
+ * The default pattern is used for the conversion.
*
* @param value The input object to be converted
* @return The converted value
@@ -174,7 +175,7 @@
* Convert the specified locale-sensitive input object into an output object.
*
* @param value The input object to be converted
- * @param pattern The pattern is used for the convertion
+ * @param pattern The pattern is used for the conversion
* @return The converted value
*
* @exception ConversionException if conversion cannot be performed
@@ -188,6 +189,7 @@
* Convert the specified locale-sensitive input object into an output object of the
* specified type. The default pattern is used for the convertion.
*
+ * @param <T> The desired target type of the conversion
* @param type Data type to which this value should be converted
* @param value The input object to be converted
* @return The converted value
@@ -195,7 +197,7 @@
* @exception ConversionException if conversion cannot be performed
* successfully
*/
- public Object convert(Class type, Object value) {
+ public <T> T convert(Class<T> type, Object value) {
return convert(type, value, null);
}
@@ -203,6 +205,7 @@
* Convert the specified locale-sensitive input object into an output object of the
* specified type.
*
+ * @param <T> The desired target type of the conversion
* @param type Data is type to which this value should be converted
* @param value is the input object to be converted
* @param pattern is the pattern is used for the conversion; if null is
@@ -213,10 +216,11 @@
* @exception ConversionException if conversion cannot be performed
* successfully
*/
- public Object convert(Class type, Object value, String pattern) {
+ public <T> T convert(Class<T> type, Object value, String pattern) {
+ Class<T> targetType = ConvertUtils.primitiveToWrapper(type);
if (value == null) {
if (useDefault) {
- return (defaultValue);
+ return getDefaultAs(targetType);
} else {
// symmetric beanutils function allows null
// so do not: throw new ConversionException("No value specified");
@@ -227,13 +231,13 @@
try {
if (pattern != null) {
- return parse(value, pattern);
+ return checkConversionResult(targetType, parse(value, pattern));
} else {
- return parse(value, this.pattern);
+ return checkConversionResult(targetType, parse(value, this.pattern));
}
} catch (Exception e) {
if (useDefault) {
- return (defaultValue);
+ return getDefaultAs(targetType);
} else {
if (e instanceof ConversionException) {
throw (ConversionException)e;
@@ -242,4 +246,44 @@
}
}
}
+
+ /**
+ * Returns the default object specified for this converter cast for the
+ * given target type. If the default value is not conform to the given type,
+ * an exception is thrown.
+ *
+ * @param <T> the desired target type
+ * @param type the target class of the conversion
+ * @return the default value in the given target type
+ * @throws ConversionException if the default object is not compatible with
+ * the target type
+ */
+ private <T> T getDefaultAs(Class<T> type) {
+ return checkConversionResult(type, defaultValue);
+ }
+
+ /**
+ * Checks whether the result of a conversion is conform to the specified
+ * target type. If this is the case, the passed in result object is cast to
+ * the correct target type. Otherwise, an exception is thrown.
+ *
+ * @param <T> the desired result type
+ * @param type the target class of the conversion
+ * @param result the conversion result object
+ * @return the result cast to the target class
+ * @throws ConversionException if the result object is not compatible with
+ * the target type
+ */
+ private static <T> T checkConversionResult(Class<T> type, Object result) {
+ if (type == null) {
+ // in this case we cannot do much; the result object is returned
+ @SuppressWarnings("unchecked")
+ T temp = (T) result;
+ return temp;
+ }
+ if (type.isInstance(result)) {
+ return type.cast(result);
+ }
+ throw new ConversionException("Unsupported target type: " + type);
+ }
}
diff --git a/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtils.java b/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtils.java
index 3d5f2ec..4238f9e 100644
--- a/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtils.java
+++ b/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtils.java
@@ -18,11 +18,11 @@
package org.apache.commons.beanutils.locale;
-import org.apache.commons.beanutils.BeanUtils;
-
import java.lang.reflect.InvocationTargetException;
import java.util.Locale;
+import org.apache.commons.beanutils.BeanUtils;
+
/**
@@ -558,7 +558,7 @@
*
* @see LocaleBeanUtilsBean#definePropertyType(Object, String, String)
*/
- protected static Class definePropertyType(Object target, String name, String propName)
+ protected static Class<?> definePropertyType(Object target, String name, String propName)
throws IllegalAccessException, InvocationTargetException {
return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().definePropertyType(target, name, propName);
@@ -577,7 +577,7 @@
* @return The converted value
* @see LocaleBeanUtilsBean#convert(Class, int, Object, String)
*/
- protected static Object convert(Class type, int index, Object value, String pattern) {
+ protected static Object convert(Class<?> type, int index, Object value, String pattern) {
return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().convert(type, index, value, pattern);
}
@@ -593,7 +593,7 @@
* @return The converted value
* @see LocaleBeanUtilsBean#convert(Class, int, Object)
*/
- protected static Object convert(Class type, int index, Object value) {
+ protected static Object convert(Class<?> type, int index, Object value) {
return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().convert(type, index, value);
}
diff --git a/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtilsBean.java b/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtilsBean.java
index 54c4d02..e206e06 100644
--- a/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtilsBean.java
+++ b/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtilsBean.java
@@ -18,7 +18,13 @@
package org.apache.commons.beanutils.locale;
+import java.beans.IndexedPropertyDescriptor;
+import java.beans.PropertyDescriptor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Locale;
+
import org.apache.commons.beanutils.BeanUtilsBean;
+import org.apache.commons.beanutils.ContextClassLoaderLocal;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.DynaBean;
@@ -26,16 +32,10 @@
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.MappedPropertyDescriptor;
import org.apache.commons.beanutils.PropertyUtilsBean;
-import org.apache.commons.beanutils.ContextClassLoaderLocal;
import org.apache.commons.beanutils.expression.Resolver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import java.beans.IndexedPropertyDescriptor;
-import java.beans.PropertyDescriptor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Locale;
-
/**
* <p>Utility methods for populating JavaBeans properties
@@ -50,11 +50,11 @@
/**
* Contains <code>LocaleBeanUtilsBean</code> instances indexed by context classloader.
*/
- private static final ContextClassLoaderLocal
- LOCALE_BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal() {
+ private static final ContextClassLoaderLocal<LocaleBeanUtilsBean>
+ LOCALE_BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal<LocaleBeanUtilsBean>() {
// Creates the default instance used when the context classloader is unavailable
@Override
- protected Object initialValue() {
+ protected LocaleBeanUtilsBean initialValue() {
return new LocaleBeanUtilsBean();
}
};
@@ -65,7 +65,7 @@
* @return the singleton instance
*/
public static LocaleBeanUtilsBean getLocaleBeanUtilsInstance() {
- return (LocaleBeanUtilsBean)LOCALE_BEANS_BY_CLASSLOADER.get();
+ return LOCALE_BEANS_BY_CLASSLOADER.get();
}
/**
@@ -312,7 +312,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
public String getSimpleProperty(Object bean, String name, String pattern)
throws IllegalAccessException, InvocationTargetException,
@@ -336,7 +336,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
@Override
public String getSimpleProperty(Object bean, String name)
@@ -363,7 +363,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
public String getMappedProperty(
Object bean,
@@ -395,7 +395,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
@Override
public String getMappedProperty(Object bean,
@@ -426,7 +426,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
public String getMappedPropertyLocale(
Object bean,
@@ -461,7 +461,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
@Override
public String getMappedProperty(Object bean, String name)
@@ -490,7 +490,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
public String getNestedProperty(
Object bean,
@@ -521,7 +521,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
@Override
public String getNestedProperty(Object bean, String name)
@@ -549,7 +549,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
public String getProperty(Object bean, String name, String pattern)
throws
@@ -576,7 +576,7 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
* @exception NoSuchMethodException if an accessor method for this
- * propety cannot be found
+ * property cannot be found
*/
@Override
public String getProperty(Object bean, String name)
@@ -687,7 +687,7 @@
int index = resolver.getIndex(name); // Indexed subscript value (if any)
String key = resolver.getKey(name); // Mapped key value (if any)
- Class type = definePropertyType(target, name, propName);
+ Class<?> type = definePropertyType(target, name, propName);
if (type != null) {
Object newValue = convert(type, index, value, pattern);
invokeSetter(target, propName, key, index, newValue);
@@ -707,10 +707,10 @@
* @exception InvocationTargetException if the property accessor method
* throws an exception
*/
- protected Class definePropertyType(Object target, String name, String propName)
+ protected Class<?> definePropertyType(Object target, String name, String propName)
throws IllegalAccessException, InvocationTargetException {
- Class type = null; // Java type of target property
+ Class<?> type = null; // Java type of target property
if (target instanceof DynaBean) {
DynaClass dynaClass = ((DynaBean) target).getDynaClass();
@@ -757,7 +757,7 @@
* @param pattern The conversion pattern
* @return The converted value
*/
- protected Object convert(Class type, int index, Object value, String pattern) {
+ protected Object convert(Class<?> type, int index, Object value, String pattern) {
if (log.isTraceEnabled()) {
log.trace("Converting value '" + value + "' to type:" + type);
@@ -814,7 +814,7 @@
* @param value The value to be converted
* @return The converted value
*/
- protected Object convert(Class type, int index, Object value) {
+ protected Object convert(Class<?> type, int index, Object value) {
Object newValue = null;
diff --git a/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtils.java b/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtils.java
index e7914a1..6108f80 100644
--- a/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtils.java
+++ b/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtils.java
@@ -17,10 +17,10 @@
package org.apache.commons.beanutils.locale;
-import org.apache.commons.collections.FastHashMap;
-
import java.util.Locale;
+import org.apache.commons.collections.FastHashMap;
+
/**
* <p>Utility methods for converting locale-sensitive String scalar values to objects of the
* specified Class, String arrays to arrays of the specified Class and
@@ -147,7 +147,7 @@
* @return the converted value
* @see LocaleConvertUtilsBean#convert(String, Class)
*/
- public static Object convert(String value, Class clazz) {
+ public static Object convert(String value, Class<?> clazz) {
return LocaleConvertUtilsBean.getInstance().convert(value, clazz);
}
@@ -165,7 +165,7 @@
* @return the converted value
* @see LocaleConvertUtilsBean#convert(String, Class, String)
*/
- public static Object convert(String value, Class clazz, String pattern) {
+ public static Object convert(String value, Class<?> clazz, String pattern) {
return LocaleConvertUtilsBean.getInstance().convert(value, clazz, pattern);
}
@@ -184,7 +184,7 @@
* @return the converted value
* @see LocaleConvertUtilsBean#convert(String, Class, Locale, String)
*/
- public static Object convert(String value, Class clazz, Locale locale, String pattern) {
+ public static Object convert(String value, Class<?> clazz, Locale locale, String pattern) {
return LocaleConvertUtilsBean.getInstance().convert(value, clazz, locale, pattern);
}
@@ -201,7 +201,7 @@
* @return the converted value
* @see LocaleConvertUtilsBean#convert(String[], Class, String)
*/
- public static Object convert(String[] values, Class clazz, String pattern) {
+ public static Object convert(String[] values, Class<?> clazz, String pattern) {
return LocaleConvertUtilsBean.getInstance().convert(values, clazz, pattern);
}
@@ -217,7 +217,7 @@
* @return the converted value
* @see LocaleConvertUtilsBean#convert(String[], Class)
*/
- public static Object convert(String[] values, Class clazz) {
+ public static Object convert(String[] values, Class<?> clazz) {
return LocaleConvertUtilsBean.getInstance().convert(values, clazz);
}
@@ -235,7 +235,7 @@
* @return the converted value
* @see LocaleConvertUtilsBean#convert(String[], Class, Locale, String)
*/
- public static Object convert(String[] values, Class clazz, Locale locale, String pattern) {
+ public static Object convert(String[] values, Class<?> clazz, Locale locale, String pattern) {
return LocaleConvertUtilsBean.getInstance().convert(values, clazz, locale, pattern);
}
@@ -252,7 +252,7 @@
* @param locale The locale
* @see LocaleConvertUtilsBean#register(LocaleConverter, Class, Locale)
*/
- public static void register(LocaleConverter converter, Class clazz, Locale locale) {
+ public static void register(LocaleConverter converter, Class<?> clazz, Locale locale) {
LocaleConvertUtilsBean.getInstance().register(converter, clazz, locale);
}
@@ -293,7 +293,7 @@
* @param locale The locale
* @see LocaleConvertUtilsBean#deregister(Class, Locale)
*/
- public static void deregister(Class clazz, Locale locale) {
+ public static void deregister(Class<?> clazz, Locale locale) {
LocaleConvertUtilsBean.getInstance().deregister(clazz, locale);
}
@@ -310,7 +310,7 @@
* @return The registered locale Converter, if any
* @see LocaleConvertUtilsBean#lookup(Class, Locale)
*/
- public static LocaleConverter lookup(Class clazz, Locale locale) {
+ public static LocaleConverter lookup(Class<?> clazz, Locale locale) {
return LocaleConvertUtilsBean.getInstance().lookup(clazz, locale);
}
diff --git a/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsBean.java b/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsBean.java
index a549e1e..44a8145 100644
--- a/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsBean.java
+++ b/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsBean.java
@@ -17,6 +17,14 @@
package org.apache.commons.beanutils.locale;
+import java.lang.reflect.Array;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.locale.converters.BigDecimalLocaleConverter;
import org.apache.commons.beanutils.locale.converters.BigIntegerLocaleConverter;
@@ -26,23 +34,14 @@
import org.apache.commons.beanutils.locale.converters.IntegerLocaleConverter;
import org.apache.commons.beanutils.locale.converters.LongLocaleConverter;
import org.apache.commons.beanutils.locale.converters.ShortLocaleConverter;
-import org.apache.commons.beanutils.locale.converters.StringLocaleConverter;
import org.apache.commons.beanutils.locale.converters.SqlDateLocaleConverter;
import org.apache.commons.beanutils.locale.converters.SqlTimeLocaleConverter;
import org.apache.commons.beanutils.locale.converters.SqlTimestampLocaleConverter;
-
+import org.apache.commons.beanutils.locale.converters.StringLocaleConverter;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import java.lang.reflect.Array;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
/**
* <p>Utility methods for converting locale-sensitive String scalar values to objects of the
* specified Class, String arrays to arrays of the specified Class and
@@ -214,7 +213,7 @@
LocaleConverter converter = lookup(String.class, locale);
- return (String) converter.convert(String.class, value, pattern);
+ return converter.convert(String.class, value, pattern);
}
/**
@@ -228,7 +227,7 @@
* @throws org.apache.commons.beanutils.ConversionException if thrown by an
* underlying Converter
*/
- public Object convert(String value, Class clazz) {
+ public Object convert(String value, Class<?> clazz) {
return convert(value, clazz, defaultLocale, null);
}
@@ -246,7 +245,7 @@
* @throws org.apache.commons.beanutils.ConversionException if thrown by an
* underlying Converter
*/
- public Object convert(String value, Class clazz, String pattern) {
+ public Object convert(String value, Class<?> clazz, String pattern) {
return convert(value, clazz, defaultLocale, pattern);
}
@@ -265,7 +264,7 @@
* @throws org.apache.commons.beanutils.ConversionException if thrown by an
* underlying Converter
*/
- public Object convert(String value, Class clazz, Locale locale, String pattern) {
+ public Object convert(String value, Class<?> clazz, Locale locale, String pattern) {
if (log.isDebugEnabled()) {
log.debug("Convert string " + value + " to class " +
@@ -273,16 +272,18 @@
" locale and " + pattern + " pattern");
}
+ Class<?> targetClass = clazz;
LocaleConverter converter = lookup(clazz, locale);
if (converter == null) {
converter = lookup(String.class, locale);
+ targetClass = String.class;
}
if (log.isTraceEnabled()) {
log.trace(" Using converter " + converter);
}
- return (converter.convert(clazz, value, pattern));
+ return (converter.convert(targetClass, value, pattern));
}
/**
@@ -297,7 +298,7 @@
* @throws org.apache.commons.beanutils.ConversionException if thrown by an
* underlying Converter
*/
- public Object convert(String[] values, Class clazz, String pattern) {
+ public Object convert(String[] values, Class<?> clazz, String pattern) {
return convert(values, clazz, getDefaultLocale(), pattern);
}
@@ -313,7 +314,7 @@
* @throws org.apache.commons.beanutils.ConversionException if thrown by an
* underlying Converter
*/
- public Object convert(String[] values, Class clazz) {
+ public Object convert(String[] values, Class<?> clazz) {
return convert(values, clazz, getDefaultLocale(), null);
}
@@ -331,9 +332,9 @@
* @throws org.apache.commons.beanutils.ConversionException if thrown by an
* underlying Converter
*/
- public Object convert(String[] values, Class clazz, Locale locale, String pattern) {
+ public Object convert(String[] values, Class<?> clazz, Locale locale, String pattern) {
- Class type = clazz;
+ Class<?> type = clazz;
if (clazz.isArray()) {
type = clazz.getComponentType();
}
@@ -360,7 +361,7 @@
* Converter
* @param locale The locale
*/
- public void register(LocaleConverter converter, Class clazz, Locale locale) {
+ public void register(LocaleConverter converter, Class<?> clazz, Locale locale) {
lookup(locale).put(clazz, converter);
}
@@ -398,7 +399,7 @@
* @param clazz Class for which to remove a registered Converter
* @param locale The locale
*/
- public void deregister(Class clazz, Locale locale) {
+ public void deregister(Class<?> clazz, Locale locale) {
lookup(locale).remove(clazz);
}
@@ -412,7 +413,7 @@
* @param locale The Locale
* @return The registered locale Converter, if any
*/
- public LocaleConverter lookup(Class clazz, Locale locale) {
+ public LocaleConverter lookup(Class<?> clazz, Locale locale) {
LocaleConverter converter = (LocaleConverter) lookup(locale).get(clazz);
@@ -511,9 +512,9 @@
*/
private static class DelegateFastHashMap extends FastHashMap {
- private final Map map;
+ private final Map<Object, Object> map;
- private DelegateFastHashMap(Map map) {
+ private DelegateFastHashMap(Map<Object, Object> map) {
this.map = map;
}
@Override
@@ -529,7 +530,7 @@
return map.containsValue(value);
}
@Override
- public Set entrySet() {
+ public Set<Map.Entry<Object, Object>> entrySet() {
return map.entrySet();
}
@Override
@@ -549,13 +550,16 @@
return map.isEmpty();
}
@Override
- public Set keySet() {
+ public Set<Object> keySet() {
return map.keySet();
}
@Override
public Object put(Object key, Object value) {
return map.put(key, value);
}
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ // we operate on very generic types (<Object, Object>), so there is
+ // no need for doing type checks
@Override
public void putAll(Map m) {
map.putAll(m);
@@ -569,7 +573,7 @@
return map.size();
}
@Override
- public Collection values() {
+ public Collection<Object> values() {
return map.values();
}
@Override
diff --git a/src/main/java/org/apache/commons/beanutils/locale/LocaleConverter.java b/src/main/java/org/apache/commons/beanutils/locale/LocaleConverter.java
index bee5d45..4ef11f1 100644
--- a/src/main/java/org/apache/commons/beanutils/locale/LocaleConverter.java
+++ b/src/main/java/org/apache/commons/beanutils/locale/LocaleConverter.java
@@ -35,13 +35,14 @@
* Convert the specified locale-sensitive input object into an output object of the
* specified type.
*
+ * @param <T> The desired target type of the conversion
* @param type Data type to which this value should be converted
* @param value The input value to be converted
* @param pattern The user-defined pattern is used for the input object formatting.
* @return The converted value
*
* @exception org.apache.commons.beanutils.ConversionException if conversion
- * cannot be performed successfully
+ * cannot be performed successfully or if the target type is not supported
*/
- public Object convert(Class type, Object value, String pattern);
+ public <T> T convert(Class<T> type, Object value, String pattern);
}
diff --git a/src/test/java/org/apache/commons/beanutils/BeanComparatorTestCase.java b/src/test/java/org/apache/commons/beanutils/BeanComparatorTestCase.java
index 9e455d7..7504f00 100644
--- a/src/test/java/org/apache/commons/beanutils/BeanComparatorTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/BeanComparatorTestCase.java
@@ -41,12 +41,6 @@
protected AlphaBean alphaBean1 = null;
protected AlphaBean alphaBean2 = null;
- // The test BeanComparator
- protected BeanComparator beanComparator = null;
-
-
-
-
// ---------------------------------------------------------- Constructors
@@ -91,7 +85,6 @@
bean = null;
alphaBean1 = null;
alphaBean2 = null;
- beanComparator = null;
}
@@ -102,62 +95,46 @@
* tests comparing two beans via their name using the default Comparator
*/
public void testSimpleCompare() {
- try {
- beanComparator = new BeanComparator("name");
- int result = beanComparator.compare(alphaBean1, alphaBean2);
- assertTrue("Comparator did not sort properly. Result:" + result,result==-1);
-
- }
- catch (Exception e) {
- fail("Exception");
- }
+ BeanComparator<AlphaBean> beanComparator = new BeanComparator<AlphaBean>(
+ "name");
+ int result = beanComparator.compare(alphaBean1, alphaBean2);
+ assertTrue("Comparator did not sort properly. Result:" + result,
+ result == -1);
}
/**
* tests comparing two beans via their name using the default Comparator, but the inverse
*/
public void testSimpleCompareInverse() {
- try {
- beanComparator = new BeanComparator("name");
- int result = beanComparator.compare(alphaBean2, alphaBean1);
- assertTrue("Comparator did not sort properly. Result:" + result,result==1);
-
- }
- catch (Exception e) {
- fail("Exception" + e);
- }
+ BeanComparator<AlphaBean> beanComparator = new BeanComparator<AlphaBean>(
+ "name");
+ int result = beanComparator.compare(alphaBean2, alphaBean1);
+ assertTrue("Comparator did not sort properly. Result:" + result,
+ result == 1);
}
/**
* tests comparing two beans via their name using the default Comparator where they have the same value.
*/
public void testCompareIdentical() {
- try {
- alphaBean1 = new AlphaBean("alphabean");
- alphaBean2 = new AlphaBean("alphabean");
- beanComparator = new BeanComparator("name");
- int result = beanComparator.compare(alphaBean1, alphaBean2);
- assertTrue("Comparator did not sort properly. Result:" + result,result==0);
-
- }
- catch (Exception e) {
- fail("Exception");
- }
+ alphaBean1 = new AlphaBean("alphabean");
+ alphaBean2 = new AlphaBean("alphabean");
+ BeanComparator<AlphaBean> beanComparator = new BeanComparator<AlphaBean>(
+ "name");
+ int result = beanComparator.compare(alphaBean1, alphaBean2);
+ assertTrue("Comparator did not sort properly. Result:" + result,
+ result == 0);
}
/**
* tests comparing one bean against itself.
*/
public void testCompareBeanAgainstSelf() {
- try {
- beanComparator = new BeanComparator("name");
- int result = beanComparator.compare(alphaBean1, alphaBean1);
- assertTrue("Comparator did not sort properly. Result:" + result,result==0);
-
- }
- catch (Exception e) {
- fail("Exception");
- }
+ BeanComparator<AlphaBean> beanComparator = new BeanComparator<AlphaBean>(
+ "name");
+ int result = beanComparator.compare(alphaBean1, alphaBean1);
+ assertTrue("Comparator did not sort properly. Result:" + result,
+ result == 0);
}
/**
@@ -166,15 +143,13 @@
*/
public void testCompareWithNulls() {
try {
- beanComparator = new BeanComparator("name");
+ BeanComparator<AlphaBean> beanComparator = new BeanComparator<AlphaBean>("name");
beanComparator.compare(alphaBean2, null);
- // DEP not sure if this is the best way to test an exception?
fail("Should not be able to compare a null value.");
-
}
catch (Exception e) {
-
+ // expected result
}
}
@@ -183,7 +158,7 @@
*/
public void testCompareOnMissingProperty() {
try {
- beanComparator = new BeanComparator("bogusName");
+ BeanComparator<AlphaBean> beanComparator = new BeanComparator<AlphaBean>("bogusName");
beanComparator.compare(alphaBean2, alphaBean1);
fail("should not be able to compare");
@@ -205,7 +180,7 @@
testBeanA.setBooleanProperty(true);
testBeanB.setBooleanProperty(false);
- beanComparator = new BeanComparator("booleanProperty");
+ BeanComparator<TestBean> beanComparator = new BeanComparator<TestBean>("booleanProperty");
beanComparator.compare(testBeanA, testBeanB);
// **** java.lang.Boolean implements Comparable from JDK 1.5 onwards
@@ -216,44 +191,33 @@
catch (ClassCastException cce){
// Expected result
}
- catch (Exception e) {
- fail("Exception" + e);
- }
}
/**
* tests comparing two beans on a boolean property, then changing the property and testing
*/
public void testSetProperty() {
- try {
- TestBean testBeanA = new TestBean();
- TestBean testBeanB = new TestBean();
+ TestBean testBeanA = new TestBean();
+ TestBean testBeanB = new TestBean();
- testBeanA.setDoubleProperty(5.5);
- testBeanB.setDoubleProperty(1.0);
+ testBeanA.setDoubleProperty(5.5);
+ testBeanB.setDoubleProperty(1.0);
- beanComparator = new BeanComparator("doubleProperty");
- int result = beanComparator.compare(testBeanA, testBeanB);
+ BeanComparator<TestBean> beanComparator = new BeanComparator<TestBean>(
+ "doubleProperty");
+ int result = beanComparator.compare(testBeanA, testBeanB);
- assertTrue("Comparator did not sort properly. Result:" + result,result==1);
+ assertTrue("Comparator did not sort properly. Result:" + result,
+ result == 1);
- testBeanA.setStringProperty("string 1");
- testBeanB.setStringProperty("string 2");
+ testBeanA.setStringProperty("string 1");
+ testBeanB.setStringProperty("string 2");
- beanComparator.setProperty("stringProperty");
+ beanComparator.setProperty("stringProperty");
- result = beanComparator.compare(testBeanA, testBeanB);
+ result = beanComparator.compare(testBeanA, testBeanB);
- assertTrue("Comparator did not sort properly. Result:" + result,result==-1);
-
- }
- catch (ClassCastException cce){
- fail("ClassCaseException " + cce.toString());
- }
- catch (Exception e) {
- fail("Exception" + e);
- }
+ assertTrue("Comparator did not sort properly. Result:" + result,
+ result == -1);
}
}
-
-
diff --git a/src/test/java/org/apache/commons/beanutils/BeanMapTestCase.java b/src/test/java/org/apache/commons/beanutils/BeanMapTestCase.java
index fb9702c..db3d473 100644
--- a/src/test/java/org/apache/commons/beanutils/BeanMapTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/BeanMapTestCase.java
@@ -19,22 +19,23 @@
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-import java.util.Map;
import java.util.HashMap;
+import java.util.Map;
import junit.framework.Test;
import junit.textui.TestRunner;
import org.apache.commons.beanutils.bugs.other.Jira87BeanFactory;
-import org.apache.commons.collections.map.AbstractTestMap;
import org.apache.commons.collections.BulkTest;
import org.apache.commons.collections.Transformer;
+import org.apache.commons.collections.map.AbstractTestMap;
/**
* Test cases for BeanMap
*
* @version $Id$
*/
+@SuppressWarnings("deprecation")
public class BeanMapTestCase extends AbstractTestMap {
public BeanMapTestCase(String testName) {
@@ -271,7 +272,7 @@
}
@Override
- public Map makeFullMap() {
+ public Map<Object, Object> makeFullMap() {
// note: These values must match (i.e. .equals() must return true)
// those returned from getSampleValues().
BeanWithProperties bean = new BeanWithProperties();
@@ -289,7 +290,7 @@
}
@Override
- public Map makeEmptyMap() {
+ public Map<Object, Object> makeEmptyMap() {
return new BeanMap();
}
@@ -361,7 +362,7 @@
public void testMethodAccessor() throws Exception {
BeanMap map = (BeanMap) makeFullMap();
- Method method = BeanWithProperties.class.getDeclaredMethod("getSomeIntegerValue", null);
+ Method method = BeanWithProperties.class.getDeclaredMethod("getSomeIntegerValue");
assertEquals(method, map.getReadMethod("someIntegerValue"));
}
@@ -390,7 +391,6 @@
* Test the default transformers via the public static Map instance
*/
public void testGetDefaultTransformersMap() {
- BeanMap beanMap = new BeanMap();
assertEquals("Boolean.TYPE", Boolean.TRUE, ((Transformer)BeanMap.defaultTransformers.get(Boolean.TYPE)).transform("true"));
assertEquals("Character.TYPE", new Character('B'), ((Transformer)BeanMap.defaultTransformers.get(Character.TYPE)).transform("BCD"));
assertEquals("Byte.TYPE", new Byte((byte)1), ((Transformer)BeanMap.defaultTransformers.get(Byte.TYPE)).transform("1"));
@@ -428,7 +428,7 @@
// expected result
}
try {
- BeanMap.defaultTransformers.putAll(new HashMap());
+ BeanMap.defaultTransformers.putAll(new HashMap<Object, Object>());
fail("putAll() - expected UnsupportedOperationException");
} catch(UnsupportedOperationException e) {
// expected result
@@ -513,7 +513,7 @@
}
/**
- * Test that the cause of exception thrown by put() is initialised.
+ * Test that the cause of exception thrown by put() is initialized.
*/
public void testExceptionThrowFromPut() {
@@ -523,7 +523,7 @@
}
try {
- Map map = new BeanMap(new BeanThrowingExceptions());
+ Map<Object, Object> map = new BeanMap(new BeanThrowingExceptions());
map.put("valueThrowingException", "value");
fail("Setter exception - expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
diff --git a/src/test/java/org/apache/commons/beanutils/BeanUtilsBenchCase.java b/src/test/java/org/apache/commons/beanutils/BeanUtilsBenchCase.java
index 6c50b9c..29f2552 100644
--- a/src/test/java/org/apache/commons/beanutils/BeanUtilsBenchCase.java
+++ b/src/test/java/org/apache/commons/beanutils/BeanUtilsBenchCase.java
@@ -22,8 +22,9 @@
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-import junit.framework.TestCase;
+
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
@@ -63,8 +64,8 @@
// Input objects that have identical sets of properties and values.
private BenchBean inBean = null;
private DynaBean inDyna = null;
- private Map inMap = null; // Map of Objects requiring no conversion
- private Map inStrs = null; // Map of Strings requiring conversion
+ private Map<String, Object> inMap = null; // Map of Objects requiring no conversion
+ private Map<String, String> inStrs = null; // Map of Strings requiring conversion
// Output objects that have identical sets of properties.
private BenchBean outBean = null;
@@ -105,7 +106,7 @@
// Create input instances
inBean = new BenchBean();
- inMap = new HashMap();
+ inMap = new HashMap<String, Object>();
inMap.put("booleanProperty", new Boolean(inBean.getBooleanProperty()));
inMap.put("byteProperty", new Byte(inBean.getByteProperty()));
inMap.put("doubleProperty", new Double(inBean.getDoubleProperty()));
@@ -115,24 +116,24 @@
inMap.put("shortProperty", new Short(inBean.getShortProperty()));
inMap.put("stringProperty", inBean.getStringProperty());
inDyna = dynaClass.newInstance();
- Iterator inKeys = inMap.keySet().iterator();
+ Iterator<String> inKeys = inMap.keySet().iterator();
while (inKeys.hasNext()) {
- String inKey = (String) inKeys.next();
+ String inKey = inKeys.next();
inDyna.set(inKey, inMap.get(inKey));
}
- inStrs = new HashMap();
+ inStrs = new HashMap<String, String>();
inKeys = inMap.keySet().iterator();
while (inKeys.hasNext()) {
- String inKey = (String) inKeys.next();
+ String inKey = inKeys.next();
inStrs.put(inKey, inMap.get(inKey).toString());
}
// Create output instances
outBean = new BenchBean();
outDyna = dynaClass.newInstance();
- Iterator outKeys = inMap.keySet().iterator();
+ Iterator<String> outKeys = inMap.keySet().iterator();
while (outKeys.hasNext()) {
- String outKey = (String) outKeys.next();
+ String outKey = outKeys.next();
outDyna.set(outKey, inMap.get(outKey));
}
diff --git a/src/test/java/org/apache/commons/beanutils/BeanUtilsTestCase.java b/src/test/java/org/apache/commons/beanutils/BeanUtilsTestCase.java
index 4eb3e1a..52e7cca 100644
--- a/src/test/java/org/apache/commons/beanutils/BeanUtilsTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/BeanUtilsTestCase.java
@@ -26,13 +26,13 @@
import java.util.Map;
import java.util.StringTokenizer;
-import org.apache.commons.beanutils.converters.ArrayConverter;
-import org.apache.commons.beanutils.converters.DateConverter;
-
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.apache.commons.beanutils.converters.ArrayConverter;
+import org.apache.commons.beanutils.converters.DateConverter;
+
/**
* <p>
@@ -257,7 +257,7 @@
*/
public void testCopyPropertiesMap() {
- Map map = new HashMap();
+ Map<String, Object> map = new HashMap<String, Object>();
map.put("booleanProperty", "false");
map.put("byteProperty", "111");
map.put("doubleProperty", "333.0");
@@ -386,7 +386,7 @@
*/
public void testDescribe() {
- Map map = null;
+ Map<String, String> map = null;
try {
map = BeanUtils.describe(bean);
} catch (Exception e) {
@@ -404,28 +404,28 @@
// Verify the values of scalar properties
assertEquals("Value of 'booleanProperty'",
"true",
- (String) map.get("booleanProperty"));
+ map.get("booleanProperty"));
assertEquals("Value of 'byteProperty'",
"121",
- (String) map.get("byteProperty"));
+ map.get("byteProperty"));
assertEquals("Value of 'doubleProperty'",
"321.0",
- (String) map.get("doubleProperty"));
+ map.get("doubleProperty"));
assertEquals("Value of 'floatProperty'",
"123.0",
- (String) map.get("floatProperty"));
+ map.get("floatProperty"));
assertEquals("Value of 'intProperty'",
"123",
- (String) map.get("intProperty"));
+ map.get("intProperty"));
assertEquals("Value of 'longProperty'",
"321",
- (String) map.get("longProperty"));
+ map.get("longProperty"));
assertEquals("Value of 'shortProperty'",
"987",
- (String) map.get("shortProperty"));
+ map.get("shortProperty"));
assertEquals("Value of 'stringProperty'",
"This is a string",
- (String) map.get("stringProperty"));
+ map.get("stringProperty"));
}
@@ -456,7 +456,6 @@
// Test comma delimited list
- String value1 = "ABC";
bean.setStringProperty("ABC");
arr = BeanUtils.getArrayProperty(bean, "stringProperty");
assertEquals("Delimited List Test lth", 1, arr.length);
@@ -626,7 +625,7 @@
try {
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
map.put("intIndexed[0]", "100");
map.put("intIndexed[2]", "120");
map.put("intIndexed[4]", "140");
@@ -677,7 +676,7 @@
try {
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
int intArray[] = new int[] { 123, 456, 789 };
map.put("intArray", intArray);
String stringArray[] = new String[]
@@ -715,7 +714,7 @@
try {
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
map.put("mappedProperty(First Key)", "New First Value");
map.put("mappedProperty(Third Key)", "New Third Value");
@@ -749,7 +748,7 @@
try {
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
map.put("nested.booleanProperty", "false");
// booleanSecond is left at true
map.put("nested.doubleProperty", "432.0");
@@ -805,7 +804,7 @@
bean.setNullProperty("Non-null value");
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
map.put("booleanProperty", "false");
// booleanSecond is left at true
map.put("byteProperty", "111");
@@ -1370,10 +1369,10 @@
*/
public void testCopyPropertyNestedMappedMap() throws Exception {
- Map origMap = new HashMap();
+ Map<String, Object> origMap = new HashMap<String, Object>();
origMap.put("First Key", "First Value");
origMap.put("Second Key", "Second Value");
- Map changedMap = new HashMap();
+ Map<String, Object> changedMap = new HashMap<String, Object>();
changedMap.put("First Key", "First Value");
changedMap.put("Second Key", "Second Value");
@@ -1477,19 +1476,19 @@
*/
public void testSetMappedMap() {
TestBean bean = new TestBean();
- Map map = new HashMap();
+ Map<String, Object> map = new HashMap<String, Object>();
map.put("sub-key-1", "sub-value-1");
map.put("sub-key-2", "sub-value-2");
map.put("sub-key-3", "sub-value-3");
bean.getMapProperty().put("mappedMap", map);
- assertEquals("BEFORE", "sub-value-3", ((Map)bean.getMapProperty().get("mappedMap")).get("sub-key-3"));
+ assertEquals("BEFORE", "sub-value-3", ((Map<?, ?>)bean.getMapProperty().get("mappedMap")).get("sub-key-3"));
try {
BeanUtils.setProperty(bean, "mapProperty(mappedMap)(sub-key-3)", "SUB-KEY-3-UPDATED");
} catch (Throwable t) {
fail("Threw " + t + "");
}
- assertEquals("AFTER", "SUB-KEY-3-UPDATED", ((Map)bean.getMapProperty().get("mappedMap")).get("sub-key-3"));
+ assertEquals("AFTER", "SUB-KEY-3-UPDATED", ((Map<?, ?>)bean.getMapProperty().get("mappedMap")).get("sub-key-3"));
}
/** Tests that separate instances can register separate instances */
@@ -1569,10 +1568,10 @@
// Ensure that the actual Map matches the expected Map
- protected void checkMap(Map actual, Map expected) {
+ protected void checkMap(Map<?, ?> actual, Map<?, ?> expected) {
assertNotNull("actual map not null", actual);
assertEquals("actual map size", expected.size(), actual.size());
- Iterator keys = expected.keySet().iterator();
+ Iterator<?> keys = expected.keySet().iterator();
while (keys.hasNext()) {
Object key = keys.next();
assertEquals("actual map value(" + key + ")",
diff --git a/src/test/java/org/apache/commons/beanutils/BeanificationTestCase.java b/src/test/java/org/apache/commons/beanutils/BeanificationTestCase.java
index 1dc545d..aaf2974 100644
--- a/src/test/java/org/apache/commons/beanutils/BeanificationTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/BeanificationTestCase.java
@@ -17,13 +17,13 @@
package org.apache.commons.beanutils;
-import java.lang.ref.WeakReference;
import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
-import junit.framework.TestCase;
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.logging.LogFactory;
@@ -97,8 +97,9 @@
// test methodology
// many thanks to Juozas Baliuka for suggesting this method
ClassLoader loader = new ClassLoader(this.getClass().getClassLoader()) {};
- WeakReference reference = new WeakReference(loader);
- Class myClass = loader.loadClass("org.apache.commons.beanutils.BetaBean");
+ WeakReference<ClassLoader> reference = new WeakReference<ClassLoader>(loader);
+ @SuppressWarnings("unused")
+ Class<?> myClass = loader.loadClass("org.apache.commons.beanutils.BetaBean");
assertNotNull("Weak reference released early", reference.get());
@@ -118,6 +119,7 @@
} else {
// create garbage:
+ @SuppressWarnings("unused")
byte[] b = new byte[bytz];
bytz = bytz * 2;
}
@@ -135,13 +137,13 @@
// many thanks to Juozas Baliuka for suggesting this methodology
TestClassLoader loader = new TestClassLoader();
- ReferenceQueue queue = new ReferenceQueue();
- WeakReference loaderReference = new WeakReference(loader, queue);
+ ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
+ WeakReference<ClassLoader> loaderReference = new WeakReference<ClassLoader>(loader, queue);
Integer test = new Integer(1);
- WeakReference testReference = new WeakReference(test, queue);
+ WeakReference<Integer> testReference = new WeakReference<Integer>(test, queue);
//Map map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.HARD, true);
- Map map = new WeakHashMap();
+ Map<Object, Object> map = new WeakHashMap<Object, Object>();
map.put(loader, test);
assertEquals("In map", test, map.get(loader));
@@ -168,6 +170,7 @@
} else {
// create garbage:
+ @SuppressWarnings("unused")
byte[] b = new byte[bytz];
bytz = bytz * 2;
}
@@ -183,7 +186,7 @@
// many thanks to Juozas Baliuka for suggesting this methodology
TestClassLoader loader = new TestClassLoader();
- WeakReference loaderReference = new WeakReference(loader);
+ WeakReference<ClassLoader> loaderReference = new WeakReference<ClassLoader>(loader);
BeanUtilsBean.getInstance();
class GetBeanUtilsBeanThread extends Thread {
@@ -211,15 +214,16 @@
GetBeanUtilsBeanThread thread = new GetBeanUtilsBeanThread();
- WeakReference threadWeakReference = new WeakReference(thread);
+ @SuppressWarnings("unused")
+ WeakReference<Thread> threadWeakReference = new WeakReference<Thread>(thread);
thread.setContextClassLoader(loader);
thread.start();
thread.join();
- WeakReference beanUtilsReference = new WeakReference(thread.beanUtils);
- WeakReference propertyUtilsReference = new WeakReference(thread.propertyUtils);
- WeakReference convertUtilsReference = new WeakReference(thread.convertUtils);
+ WeakReference<BeanUtilsBean> beanUtilsReference = new WeakReference<BeanUtilsBean>(thread.beanUtils);
+ WeakReference<PropertyUtilsBean> propertyUtilsReference = new WeakReference<PropertyUtilsBean>(thread.propertyUtils);
+ WeakReference<ConvertUtilsBean> convertUtilsReference = new WeakReference<ConvertUtilsBean>(thread.convertUtils);
assertNotNull("Weak reference released early (1)", loaderReference.get());
assertNotNull("Weak reference released early (2)", beanUtilsReference.get());
@@ -249,6 +253,7 @@
} else {
// create garbage:
+ @SuppressWarnings("unused")
byte[] b = new byte[bytz];
bytz = bytz * 2;
}
@@ -314,9 +319,9 @@
class CCLLTesterThread extends Thread {
private final Signal signal;
- private final ContextClassLoaderLocal ccll;
+ private final ContextClassLoaderLocal<Integer> ccll;
- CCLLTesterThread(Signal signal, ContextClassLoaderLocal ccll) {
+ CCLLTesterThread(Signal signal, ContextClassLoaderLocal<Integer> ccll) {
this.signal = signal;
this.ccll = ccll;
}
@@ -334,7 +339,7 @@
}
}
- ContextClassLoaderLocal ccll = new ContextClassLoaderLocal();
+ ContextClassLoaderLocal<Integer> ccll = new ContextClassLoaderLocal<Integer>();
ccll.set(new Integer(1776));
assertEquals("Start thread sets value", new Integer(1776), ccll.get());
@@ -369,8 +374,8 @@
try {
signal.setSignal(3);
ConvertUtils.register(new Converter() {
- public Object convert(Class type, Object value) {
- return new Integer(9);
+ public <T> T convert(Class<T> type, Object value) {
+ return ConvertUtils.primitiveToWrapper(type).cast(new Integer(9));
}
}, Integer.TYPE);
BeanUtils.setProperty(bean, "int", new Integer(1));
@@ -391,8 +396,8 @@
assertEquals("Wrong property value (1)", 1, bean.getInt());
ConvertUtils.register(new Converter() {
- public Object convert(Class type, Object value) {
- return new Integer(5);
+ public <T> T convert(Class<T> type, Object value) {
+ return ConvertUtils.primitiveToWrapper(type).cast(new Integer(5));
}
}, Integer.TYPE);
BeanUtils.setProperty(bean, "int", new Integer(1));
@@ -461,7 +466,7 @@
/** Tests whether the unset method works*/
public void testContextClassLoaderUnset() throws Exception {
BeanUtilsBean beanOne = new BeanUtilsBean();
- ContextClassLoaderLocal ccll = new ContextClassLoaderLocal();
+ ContextClassLoaderLocal<BeanUtilsBean> ccll = new ContextClassLoaderLocal<BeanUtilsBean>();
ccll.set(beanOne);
assertEquals("Start thread gets right instance", beanOne, ccll.get());
ccll.unset();
diff --git a/src/test/java/org/apache/commons/beanutils/ConstructorUtilsTestCase.java b/src/test/java/org/apache/commons/beanutils/ConstructorUtilsTestCase.java
index 1b237a1..78480e9 100644
--- a/src/test/java/org/apache/commons/beanutils/ConstructorUtilsTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/ConstructorUtilsTestCase.java
@@ -109,7 +109,7 @@
public void testInvokeConstructorWithTypeArray() throws Exception {
{
Object[] args = { Boolean.TRUE, "TEST" };
- Class[] types = { Boolean.TYPE, String.class };
+ Class<?>[] types = { Boolean.TYPE, String.class };
Object obj = ConstructorUtils.invokeConstructor(TestBean.class,args,types);
assertNotNull(obj);
assertTrue(obj instanceof TestBean);
@@ -118,7 +118,7 @@
}
{
Object[] args = { Boolean.TRUE, "TEST" };
- Class[] types = { Boolean.class, String.class };
+ Class<?>[] types = { Boolean.class, String.class };
Object obj = ConstructorUtils.invokeConstructor(TestBean.class,args,types);
assertNotNull(obj);
assertTrue(obj instanceof TestBean);
@@ -179,7 +179,7 @@
public void testInvokeExactConstructorWithTypeArray() throws Exception {
{
Object[] args = { Boolean.TRUE, "TEST" };
- Class[] types = { Boolean.TYPE, String.class };
+ Class<?>[] types = { Boolean.TYPE, String.class };
Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class,args,types);
assertNotNull(obj);
assertTrue(obj instanceof TestBean);
@@ -188,7 +188,7 @@
}
{
Object[] args = { Boolean.TRUE, "TEST" };
- Class[] types = { Boolean.class, String.class };
+ Class<?>[] types = { Boolean.class, String.class };
Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class,args,types);
assertNotNull(obj);
assertTrue(obj instanceof TestBean);
@@ -197,7 +197,7 @@
}
{
Object[] args = { new Float(17.3f), "TEST" };
- Class[] types = { Float.TYPE, String.class };
+ Class<?>[] types = { Float.TYPE, String.class };
Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class,args,types);
assertNotNull(obj);
assertTrue(obj instanceof TestBean);
@@ -206,7 +206,7 @@
}
{
Object[] args = { new Float(17.3f), "TEST" };
- Class[] types = { Float.class, String.class };
+ Class<?>[] types = { Float.class, String.class };
try {
ConstructorUtils.invokeExactConstructor(TestBean.class,args,types);
fail("Expected NoSuchMethodException");
@@ -218,54 +218,54 @@
public void testGetAccessibleConstructor() throws Exception {
{
- Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,String.class);
+ Constructor<?> ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,String.class);
assertNotNull(ctor);
assertTrue(Modifier.isPublic(ctor.getModifiers()));
}
{
- Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,Integer.class);
+ Constructor<?> ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,Integer.class);
assertNotNull(ctor);
assertTrue(Modifier.isPublic(ctor.getModifiers()));
}
{
- Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,Integer.TYPE);
+ Constructor<?> ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,Integer.TYPE);
assertNull(ctor);
}
}
public void testGetAccessibleConstructorWithTypeArray() throws Exception {
{
- Class[] types = { Boolean.TYPE, String.class };
- Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,types);
+ Class<?>[] types = { Boolean.TYPE, String.class };
+ Constructor<?> ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,types);
assertNotNull(ctor);
assertTrue(Modifier.isPublic(ctor.getModifiers()));
}
{
- Class[] types = { Boolean.TYPE, Boolean.TYPE, String.class };
- Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,types);
+ Class<?>[] types = { Boolean.TYPE, Boolean.TYPE, String.class };
+ Constructor<?> ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,types);
assertNull(ctor);
}
}
public void testGetAccessibleConstructorWithConstructorArg() throws Exception {
{
- Class[] types = { Integer.class };
- Constructor c1 = TestBean.class.getConstructor(types);
- Constructor ctor = ConstructorUtils.getAccessibleConstructor(c1);
+ Class<?>[] types = { Integer.class };
+ Constructor<?> c1 = TestBean.class.getConstructor(types);
+ Constructor<?> ctor = ConstructorUtils.getAccessibleConstructor(c1);
assertNotNull(ctor);
assertTrue(Modifier.isPublic(ctor.getModifiers()));
}
{
- Class[] types = { Integer.class };
- Constructor c1 = TestBean.class.getDeclaredConstructor(types);
- Constructor ctor = ConstructorUtils.getAccessibleConstructor(c1);
+ Class<?>[] types = { Integer.class };
+ Constructor<?> c1 = TestBean.class.getDeclaredConstructor(types);
+ Constructor<?> ctor = ConstructorUtils.getAccessibleConstructor(c1);
assertNotNull(ctor);
assertTrue(Modifier.isPublic(ctor.getModifiers()));
}
{
- Class[] types = { Integer.TYPE };
- Constructor c1 = TestBean.class.getDeclaredConstructor(types);
- Constructor ctor = ConstructorUtils.getAccessibleConstructor(c1);
+ Class<?>[] types = { Integer.TYPE };
+ Constructor<?> c1 = TestBean.class.getDeclaredConstructor(types);
+ Constructor<?> ctor = ConstructorUtils.getAccessibleConstructor(c1);
assertNull(ctor);
}
}
diff --git a/src/test/java/org/apache/commons/beanutils/ConvertUtilsTestCase.java b/src/test/java/org/apache/commons/beanutils/ConvertUtilsTestCase.java
index 4400453..275e56b 100644
--- a/src/test/java/org/apache/commons/beanutils/ConvertUtilsTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/ConvertUtilsTestCase.java
@@ -24,11 +24,13 @@
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
-import org.apache.commons.beanutils.converters.DateConverter;
-import junit.framework.TestCase;
+
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.apache.commons.beanutils.converters.DateConverter;
+
/**
* <p>
@@ -614,6 +616,8 @@
}
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ // We need to use raw types in order to test legacy converters
public void testConvertToString() throws Exception {
Converter dummyConverter = new Converter() {
public Object convert(Class type, Object value) {
@@ -658,6 +662,16 @@
}
+ /**
+ * Tests a conversion to an unsupported target type.
+ */
+ public void testConvertUnsupportedTargetType() {
+ ConvertUtilsBean utils = new ConvertUtilsBean();
+ Object value = "A test value";
+ assertSame("Got different object", value,
+ utils.convert(value, getClass()));
+ }
+
// -------------------------------------------------------- Private Methods
diff --git a/src/test/java/org/apache/commons/beanutils/DynaBeanMapDecoratorTestCase.java b/src/test/java/org/apache/commons/beanutils/DynaBeanMapDecoratorTestCase.java
index 6cf5aa1..9768ccc 100644
--- a/src/test/java/org/apache/commons/beanutils/DynaBeanMapDecoratorTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/DynaBeanMapDecoratorTestCase.java
@@ -24,6 +24,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
@@ -33,6 +34,7 @@
*
* @version $Id$
*/
+@SuppressWarnings("deprecation")
public class DynaBeanMapDecoratorTestCase extends TestCase {
private static final DynaProperty stringProp = new DynaProperty("stringProp", String.class);
@@ -47,14 +49,14 @@
private static String stringVal = "somevalue";
private static Integer intVal = new Integer(5);
private static Date dateVal = new Date();
- private final Map mapVal = new HashMap();
+ private final Map<Object, Object> mapVal = new HashMap<Object, Object>();
private final Object[] values = new Object[] {stringVal, null, intVal, dateVal, mapVal};
private BasicDynaBean dynaBean;
- private Map decoratedMap;
- private Map modifiableMap;
- private static final Map emptyMap = new DynaBeanMapDecorator(new BasicDynaBean(new BasicDynaClass()));
+ private Map<Object, Object> decoratedMap;
+ private Map<Object, Object> modifiableMap;
+ private static final Map<Object, Object> emptyMap = new DynaBeanMapDecorator(new BasicDynaBean(new BasicDynaClass()));
// ---------------------------------------------------------- Constructors
@@ -163,18 +165,20 @@
* Test entrySet() method
*/
public void testEntrySet() {
- Set set = modifiableMap.entrySet();
+ Set<Map.Entry<Object, Object>> set = modifiableMap.entrySet();
// Check the Set can't be modified
- checkUnmodifiable("entrySet()", set);
+ Map<Object, Object> m = new HashMap<Object, Object>();
+ m.put("key", "value");
+ checkUnmodifiable("entrySet()", set, m.entrySet().iterator().next());
assertEquals("entrySet size", properties.length, set.size());
- Iterator iterator = set.iterator();
- List namesList = new ArrayList();
+ Iterator<Map.Entry<Object, Object>> iterator = set.iterator();
+ List<String> namesList = new ArrayList<String>();
int i = 0;
while (iterator.hasNext()) {
- Map.Entry entry = (Map.Entry)iterator.next();
+ Map.Entry<Object, Object> entry = iterator.next();
String name = (String)entry.getKey();
namesList.add(name);
Object expectValue = decoratedMap.get(name);
@@ -216,10 +220,10 @@
* Test keySet() method
*/
public void testKeySet() {
- Set set = modifiableMap.keySet();
+ Set<Object> set = modifiableMap.keySet();
// Check the Set can't be modified
- checkUnmodifiable("keySet()", set);
+ checkUnmodifiable("keySet()", set, "xyz");
assertEquals("keySet size", properties.length, set.size());
@@ -256,7 +260,7 @@
public void testPutAll() {
String newValue = "ABC";
- Map newMap = new HashMap();
+ Map<Object, Object> newMap = new HashMap<Object, Object>();
newMap.put(stringProp.getName(), newValue);
// Test read only
@@ -303,15 +307,15 @@
* Test values() method
*/
public void testValues() {
- Collection collection = modifiableMap.values();
+ Collection<Object> collection = modifiableMap.values();
// Check the Collection can't be modified
- checkUnmodifiable("values()", collection);
+ checkUnmodifiable("values()", collection, "xyz");
assertEquals("values size", values.length, collection.size());
// Collection should be ordered in same sequence as properties
- Iterator iterator = collection.iterator();
+ Iterator<Object> iterator = collection.iterator();
int i = 0;
while (iterator.hasNext()) {
assertEquals("values("+i+")", values[i], iterator.next());
@@ -322,20 +326,18 @@
/**
* Check that a Collection is not modifiable
*/
- private void checkUnmodifiable(String desc, Collection collection) {
- String testVal = "xyz";
-
+ private <E> void checkUnmodifiable(String desc, Collection<E> collection, E addElem) {
// Check can't add()
try {
- collection.add(testVal);
+ collection.add(addElem);
fail(desc + ".add()");
} catch(UnsupportedOperationException ignore) {
// expected result
}
// Check can't addAll()
- List list = new ArrayList(1);
- list.add(testVal);
+ List<E> list = new ArrayList<E>(1);
+ list.add(addElem);
try {
collection.addAll(list);
fail(desc + ".addAll()");
diff --git a/src/test/java/org/apache/commons/beanutils/DynaBeanUtilsTestCase.java b/src/test/java/org/apache/commons/beanutils/DynaBeanUtilsTestCase.java
index 7d2b38e..c6884bb 100644
--- a/src/test/java/org/apache/commons/beanutils/DynaBeanUtilsTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/DynaBeanUtilsTestCase.java
@@ -25,8 +25,8 @@
import java.util.List;
import java.util.Map;
-import junit.framework.TestCase;
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
@@ -125,7 +125,7 @@
int intIndexed[] = { 0, 10, 20, 30, 40 };
bean.set("intIndexed", intIndexed);
bean.set("intProperty", new Integer(123));
- List listIndexed = new ArrayList();
+ List<String> listIndexed = new ArrayList<String>();
listIndexed.add("String 0");
listIndexed.add("String 1");
listIndexed.add("String 2");
@@ -133,15 +133,15 @@
listIndexed.add("String 4");
bean.set("listIndexed", listIndexed);
bean.set("longProperty", new Long(321));
- HashMap mapProperty = new HashMap();
+ HashMap<String, Object> mapProperty = new HashMap<String, Object>();
mapProperty.put("First Key", "First Value");
mapProperty.put("Second Key", "Second Value");
bean.set("mapProperty", mapProperty);
- HashMap mappedProperty = new HashMap();
+ HashMap<String, Object> mappedProperty = new HashMap<String, Object>();
mappedProperty.put("First Key", "First Value");
mappedProperty.put("Second Key", "Second Value");
bean.set("mappedProperty", mappedProperty);
- HashMap mappedIntProperty = new HashMap();
+ HashMap<String, Integer> mappedIntProperty = new HashMap<String, Integer>();
mappedIntProperty.put("One", new Integer(1));
mappedIntProperty.put("Two", new Integer(2));
bean.set("mappedIntProperty", mappedIntProperty);
@@ -344,7 +344,7 @@
*/
public void testCopyPropertiesMap() {
- Map map = new HashMap();
+ Map<String, Object> map = new HashMap<String, Object>();
map.put("booleanProperty", "false");
map.put("byteProperty", "111");
map.put("doubleProperty", "333.0");
@@ -475,7 +475,7 @@
*/
public void testDescribe() {
- Map map = null;
+ Map<String, Object> map = null;
try {
map = PropertyUtils.describe(bean);
} catch (Exception e) {
@@ -526,7 +526,7 @@
try {
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
// int intArray[] = new int[] { 123, 456, 789 };
String intArrayIn[] = new String[] { "123", "456", "789" };
map.put("intArray", intArrayIn);
@@ -698,7 +698,7 @@
try {
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
map.put("intIndexed[0]", "100");
map.put("intIndexed[2]", "120");
map.put("intIndexed[4]", "140");
@@ -758,7 +758,7 @@
try {
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
map.put("mappedProperty(First Key)", "New First Value");
map.put("mappedProperty(Third Key)", "New Third Value");
@@ -792,7 +792,7 @@
try {
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
map.put("nested.booleanProperty", "false");
// booleanSecond is left at true
map.put("nested.doubleProperty", "432.0");
@@ -845,7 +845,7 @@
bean.set("nullProperty", "non-null value");
- HashMap map = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
map.put("booleanProperty", "false");
// booleanSecond is left at true
map.put("doubleProperty", "432.0");
@@ -1150,17 +1150,17 @@
*/
public void testCopyPropertyNestedMappedMap() throws Exception {
- Map origMap = new HashMap();
+ Map<String, Object> origMap = new HashMap<String, Object>();
origMap.put("First Key", "First Value");
origMap.put("Second Key", "Second Value");
- Map changedMap = new HashMap();
+ Map<String, Object> changedMap = new HashMap<String, Object>();
changedMap.put("First Key", "First Value");
changedMap.put("Second Key", "Second Value");
// No conversion required
BeanUtils.copyProperty(bean, "nested.mapProperty(Second Key)",
"New Second Value");
- checkMap((Map) bean.get("mapProperty"), origMap);
+ checkMap((Map<?, ?>) bean.get("mapProperty"), origMap);
changedMap.put("Second Key", "New Second Value");
checkMap(((TestBean) bean.get("nested")).getMapProperty(), changedMap);
@@ -1214,10 +1214,10 @@
// Ensure that the actual Map matches the expected Map
- protected void checkMap(Map actual, Map expected) {
+ protected void checkMap(Map<?, ?> actual, Map<?, ?> expected) {
assertNotNull("actual map not null", actual);
assertEquals("actual map size", expected.size(), actual.size());
- Iterator keys = expected.keySet().iterator();
+ Iterator<?> keys = expected.keySet().iterator();
while (keys.hasNext()) {
Object key = keys.next();
assertEquals("actual map value(" + key + ")",
diff --git a/src/test/java/org/apache/commons/beanutils/DynaPropertyUtilsTestCase.java b/src/test/java/org/apache/commons/beanutils/DynaPropertyUtilsTestCase.java
index e743b49..061c3c6 100644
--- a/src/test/java/org/apache/commons/beanutils/DynaPropertyUtilsTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/DynaPropertyUtilsTestCase.java
@@ -25,8 +25,8 @@
import java.util.List;
import java.util.Map;
-import junit.framework.TestCase;
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
@@ -118,7 +118,7 @@
int intIndexed[] = { 0, 10, 20, 30, 40 };
bean.set("intIndexed", intIndexed);
bean.set("intProperty", new Integer(123));
- List listIndexed = new ArrayList();
+ List<String> listIndexed = new ArrayList<String>();
listIndexed.add("String 0");
listIndexed.add("String 1");
listIndexed.add("String 2");
@@ -126,19 +126,19 @@
listIndexed.add("String 4");
bean.set("listIndexed", listIndexed);
bean.set("longProperty", new Long(321));
- HashMap mapProperty = new HashMap();
+ HashMap<String, Object> mapProperty = new HashMap<String, Object>();
mapProperty.put("First Key", "First Value");
mapProperty.put("Second Key", "Second Value");
bean.set("mapProperty", mapProperty);
- HashMap mappedObjects = new HashMap();
+ HashMap<String, Object> mappedObjects = new HashMap<String, Object>();
mappedObjects.put("First Key", "First Value");
mappedObjects.put("Second Key", "Second Value");
bean.set("mappedObjects", mappedObjects);
- HashMap mappedProperty = new HashMap();
+ HashMap<String, Object> mappedProperty = new HashMap<String, Object>();
mappedProperty.put("First Key", "First Value");
mappedProperty.put("Second Key", "Second Value");
bean.set("mappedProperty", mappedProperty);
- HashMap mappedIntProperty = new HashMap();
+ HashMap<String, Integer> mappedIntProperty = new HashMap<String, Integer>();
mappedIntProperty.put("One", new Integer(1));
mappedIntProperty.put("Two", new Integer(2));
bean.set("mappedIntProperty", mappedIntProperty);
@@ -188,7 +188,7 @@
*/
public void testCopyPropertiesMap() {
- Map map = new HashMap();
+ Map<String, Object> map = new HashMap<String, Object>();
map.put("booleanProperty", Boolean.FALSE);
map.put("doubleProperty", new Double(333.0));
map.put("dupProperty", new String[] { "New 0", "New 1", "New 2" });
@@ -245,7 +245,7 @@
*/
public void testDescribe() {
- Map map = null;
+ Map<String, Object> map = null;
try {
map = PropertyUtils.describe(bean);
} catch (Exception e) {
@@ -1278,9 +1278,8 @@
*/
public void testGetSimpleIndexed() {
- Object value = null;
try {
- value = PropertyUtils.getSimpleProperty(bean,
+ PropertyUtils.getSimpleProperty(bean,
"intIndexed[0]");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalAccessException e) {
@@ -1355,9 +1354,8 @@
*/
public void testGetSimpleNested() {
- Object value = null;
try {
- value = PropertyUtils.getSimpleProperty(bean,
+ PropertyUtils.getSimpleProperty(bean,
"nested.stringProperty");
fail("Should have thrown IllegaArgumentException");
} catch (IllegalAccessException e) {
diff --git a/src/test/java/org/apache/commons/beanutils/DynaResultSetTestCase.java b/src/test/java/org/apache/commons/beanutils/DynaResultSetTestCase.java
index 96d7f2a..0e7e477 100644
--- a/src/test/java/org/apache/commons/beanutils/DynaResultSetTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/DynaResultSetTestCase.java
@@ -22,8 +22,8 @@
import java.math.BigDecimal;
import java.util.Iterator;
-import junit.framework.TestCase;
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
@@ -178,7 +178,7 @@
public void testIteratorCount() {
- Iterator rows = dynaClass.iterator();
+ Iterator<?> rows = dynaClass.iterator();
assertNotNull("iterator exists", rows);
int n = 0;
while (rows.hasNext()) {
@@ -196,7 +196,7 @@
public void testIteratorResults() {
// Grab the third row
- Iterator rows = dynaClass.iterator();
+ Iterator<DynaBean> rows = dynaClass.iterator();
rows.next();
rows.next();
DynaBean row = (DynaBean) rows.next();
@@ -255,7 +255,7 @@
}
// Grab the third row
- Iterator rows = dynaClass.iterator();
+ Iterator<DynaBean> rows = dynaClass.iterator();
rows.next();
rows.next();
DynaBean row = (DynaBean) rows.next();
diff --git a/src/test/java/org/apache/commons/beanutils/DynaRowSetTestCase.java b/src/test/java/org/apache/commons/beanutils/DynaRowSetTestCase.java
index e78e257..0284a3e 100644
--- a/src/test/java/org/apache/commons/beanutils/DynaRowSetTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/DynaRowSetTestCase.java
@@ -181,7 +181,7 @@
public void testListCount() {
- List rows = dynaClass.getRows();
+ List<DynaBean> rows = dynaClass.getRows();
assertNotNull("list exists", rows);
assertEquals("list row count", 5, rows.size());
@@ -191,8 +191,8 @@
public void testListResults() {
// Grab the third row
- List rows = dynaClass.getRows();
- DynaBean row = (DynaBean) rows.get(2);
+ List<DynaBean> rows = dynaClass.getRows();
+ DynaBean row = rows.get(2);
// Invalid argument test
try {
@@ -247,8 +247,8 @@
}
// Grab the third row
- List rows = dynaClass.getRows();
- DynaBean row = (DynaBean) rows.get(2);
+ List<DynaBean> rows = dynaClass.getRows();
+ DynaBean row = rows.get(2);
// Invalid argument test
try {
@@ -295,7 +295,7 @@
// created one with low limit
RowSetDynaClass limitedDynaClass = new RowSetDynaClass(TestResultSet.createProxy(), 3);
- List rows = limitedDynaClass.getRows();
+ List<DynaBean> rows = limitedDynaClass.getRows();
assertNotNull("list exists", rows);
assertEquals("limited row count", 3, rows.size());
@@ -329,8 +329,8 @@
assertEquals("Timestamp ResultSet Value", CustomTimestamp.class, resultSet.getObject("timestampProperty").getClass());
RowSetDynaClass inconsistentDynaClass = new RowSetDynaClass(resultSet);
- DynaBean firstRow = (DynaBean)inconsistentDynaClass.getRows().get(0);
- Class expectedType = null;
+ DynaBean firstRow = inconsistentDynaClass.getRows().get(0);
+ Class<?> expectedType = null;
DynaProperty property = null;
// Test Date
diff --git a/src/test/java/org/apache/commons/beanutils/ExtendMapBean.java b/src/test/java/org/apache/commons/beanutils/ExtendMapBean.java
index 5798cba..1c72a87 100644
--- a/src/test/java/org/apache/commons/beanutils/ExtendMapBean.java
+++ b/src/test/java/org/apache/commons/beanutils/ExtendMapBean.java
@@ -26,7 +26,7 @@
* @version $Id$
*/
-public class ExtendMapBean extends Hashtable {
+public class ExtendMapBean extends Hashtable<Object, Object> {
private String dbName = "[UNSET]";
diff --git a/src/test/java/org/apache/commons/beanutils/IndexedPropertyTestCase.java b/src/test/java/org/apache/commons/beanutils/IndexedPropertyTestCase.java
index 5dbe5ed..3645590 100644
--- a/src/test/java/org/apache/commons/beanutils/IndexedPropertyTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/IndexedPropertyTestCase.java
@@ -17,10 +17,10 @@
package org.apache.commons.beanutils;
-import java.util.List;
-import java.util.ArrayList;
import java.beans.IndexedPropertyDescriptor;
import java.beans.PropertyDescriptor;
+import java.util.ArrayList;
+import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
@@ -52,9 +52,9 @@
private PropertyUtilsBean propertyUtilsBean;
private String[] testArray;
private String[] newArray;
- private List testList;
- private List newList;
- private ArrayList arrayList;
+ private List<String> testList;
+ private List<Object> newList;
+ private ArrayList<Object> arrayList;
// ---------------------------------------------------------- Constructors
@@ -85,17 +85,17 @@
testArray= new String[] {"array-0", "array-1", "array-2"};
newArray = new String[] {"newArray-0", "newArray-1", "newArray-2"};
- testList = new ArrayList();
+ testList = new ArrayList<String>();
testList.add("list-0");
testList.add("list-1");
testList.add("list-2");
- newList = new ArrayList();
+ newList = new ArrayList<Object>();
newList.add("newList-0");
newList.add("newList-1");
newList.add("newList-2");
- arrayList = new ArrayList();
+ arrayList = new ArrayList<Object>();
arrayList.add("arrayList-0");
arrayList.add("arrayList-1");
arrayList.add("arrayList-2");
@@ -511,7 +511,7 @@
beanUtilsBean.setProperty(bean, "stringList", newList);
Object value = bean.getStringList();
assertEquals("Type is different", newList.getClass(), value.getClass());
- List list = (List)value;
+ List<?> list = (List<?>)value;
assertEquals("List size is different", newList.size(), list.size());
for (int i = 0; i < list.size(); i++) {
assertEquals("Element " + i + " is different", newList.get(i), list.get(i));
@@ -571,7 +571,7 @@
beanUtilsBean.setProperty(bean, "arrayList", newList);
Object value = bean.getArrayList();
assertEquals("Type is different", newList.getClass(), value.getClass());
- List list = (List)value;
+ List<?> list = (List<?>)value;
assertEquals("List size is different", newList.size(), list.size());
for (int i = 0; i < list.size(); i++) {
assertEquals("Element " + i + " is different", newList.get(i), list.get(i));
diff --git a/src/test/java/org/apache/commons/beanutils/IndexedTestBean.java b/src/test/java/org/apache/commons/beanutils/IndexedTestBean.java
index 9039588..5855358 100644
--- a/src/test/java/org/apache/commons/beanutils/IndexedTestBean.java
+++ b/src/test/java/org/apache/commons/beanutils/IndexedTestBean.java
@@ -17,8 +17,8 @@
package org.apache.commons.beanutils;
-import java.util.List;
import java.util.ArrayList;
+import java.util.List;
/**
* Indexed Properties Test bean for JUnit tests for the "beanutils" component.
@@ -28,8 +28,8 @@
public class IndexedTestBean {
private String[] stringArray;
- private List stringList;
- private ArrayList arrayList;
+ private List<String> stringList;
+ private ArrayList<Object> arrayList;
// ----------------------------------------------------------- Constructors
@@ -71,14 +71,14 @@
/**
* Getter for the java.util.List property.
*/
- public List getStringList() {
+ public List<String> getStringList() {
return stringList;
}
/**
* Setter for the java.util.List property.
*/
- public void setStringList(List stringList) {
+ public void setStringList(List<String> stringList) {
this.stringList = stringList;
}
@@ -86,7 +86,7 @@
* Indexed Getter for the java.util.List property.
*/
public String getStringList(int index) {
- return (String)stringList.get(index);
+ return stringList.get(index);
}
/**
@@ -99,14 +99,14 @@
/**
* Getter for the java.util.ArrayList property.
*/
- public ArrayList getArrayList() {
+ public ArrayList<Object> getArrayList() {
return arrayList;
}
/**
* Setter for the java.util.ArrayList property.
*/
- public void setArrayList(ArrayList arrayList) {
+ public void setArrayList(ArrayList<Object> arrayList) {
this.arrayList = arrayList;
}
diff --git a/src/test/java/org/apache/commons/beanutils/LazyDynaBeanTestCase.java b/src/test/java/org/apache/commons/beanutils/LazyDynaBeanTestCase.java
index 0316e6d..2d793bd 100644
--- a/src/test/java/org/apache/commons/beanutils/LazyDynaBeanTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/LazyDynaBeanTestCase.java
@@ -16,13 +16,14 @@
*/
package org.apache.commons.beanutils;
-import java.util.HashMap;
-import java.util.TreeMap;
-import java.util.ArrayList;
-import java.util.LinkedList;
import java.lang.reflect.InvocationTargetException;
-import junit.framework.TestCase;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.TreeMap;
+
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
@@ -170,12 +171,12 @@
bean.set(testProperty, testKey, testInteger1);
assertEquals("Check Mapped Property exists", HashMap.class, bean.get(testProperty).getClass());
assertEquals("Check First Mapped Value is correct(a)", testInteger1, bean.get(testProperty, testKey));
- assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((HashMap)bean.get(testProperty)).get(testKey));
+ assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((HashMap<?, ?>)bean.get(testProperty)).get(testKey));
// Set the property again - should set the new value
bean.set(testProperty, testKey, testInteger2);
assertEquals("Check Second Mapped Value is correct(a)", testInteger2, bean.get(testProperty, testKey));
- assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((HashMap)bean.get(testProperty)).get(testKey));
+ assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((HashMap<?, ?>)bean.get(testProperty)).get(testKey));
}
/**
@@ -197,12 +198,12 @@
bean.set(testProperty, testKey, testInteger1);
assertEquals("Check Mapped Property exists", TreeMap.class, bean.get(testProperty).getClass());
assertEquals("Check First Mapped Value is correct(a)", testInteger1, bean.get(testProperty, testKey));
- assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((TreeMap)bean.get(testProperty)).get(testKey));
+ assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((TreeMap<?, ?>)bean.get(testProperty)).get(testKey));
// Set the property again - should set the new value
bean.set(testProperty, testKey, testInteger2);
assertEquals("Check Second Mapped Value is correct(a)", testInteger2, bean.get(testProperty, testKey));
- assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((TreeMap)bean.get(testProperty)).get(testKey));
+ assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((TreeMap<?, ?>)bean.get(testProperty)).get(testKey));
}
/**
@@ -290,13 +291,13 @@
assertNotNull("Check Indexed Property is not null", bean.get(testProperty));
assertEquals("Check Indexed Property is correct type", ArrayList.class, bean.get(testProperty).getClass());
assertEquals("Check First Indexed Value is correct", testInteger1, bean.get(testProperty, index));
- assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((ArrayList)bean.get(testProperty)).size()));
+ assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((ArrayList<?>)bean.get(testProperty)).size()));
// Set a second indexed value, should automatically grow the ArrayList and set appropriate indexed value
index = index + 2;
bean.set(testProperty, index, testString1);
assertEquals("Check Second Indexed Value is correct", testString1, bean.get(testProperty, index));
- assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((ArrayList)bean.get(testProperty)).size()));
+ assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((ArrayList<?>)bean.get(testProperty)).size()));
}
/**
@@ -320,13 +321,13 @@
bean.set(testProperty, index, testString1);
assertEquals("Check Property type is correct", LinkedList.class, bean.get(testProperty).getClass());
assertEquals("Check First Indexed Value is correct", testString1, bean.get(testProperty, index));
- assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((LinkedList)bean.get(testProperty)).size()));
+ assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((LinkedList<?>)bean.get(testProperty)).size()));
// Set a second indexed value, should automatically grow the LinkedList and set appropriate indexed value
index = index + 2;
bean.set(testProperty, index, testInteger1);
assertEquals("Check Second Indexed Value is correct", testInteger1, bean.get(testProperty, index));
- assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((LinkedList)bean.get(testProperty)).size()));
+ assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((LinkedList<?>)bean.get(testProperty)).size()));
}
/**
diff --git a/src/test/java/org/apache/commons/beanutils/LazyDynaListTestCase.java b/src/test/java/org/apache/commons/beanutils/LazyDynaListTestCase.java
index 429f38a..a5dfbe5 100644
--- a/src/test/java/org/apache/commons/beanutils/LazyDynaListTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/LazyDynaListTestCase.java
@@ -16,17 +16,18 @@
*/
package org.apache.commons.beanutils;
-import java.util.List;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.TreeMap;
-import java.util.ArrayList;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-import junit.framework.TestCase;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
@@ -43,8 +44,8 @@
new DynaProperty(BASIC_PROP1, String.class),
new DynaProperty(BASIC_PROP2, HashMap.class)};
- protected DynaClass treeMapDynaClass = new LazyDynaMap(new TreeMap());
- protected DynaClass hashMapDynaClass = new LazyDynaMap(new HashMap());
+ protected DynaClass treeMapDynaClass = new LazyDynaMap(new TreeMap<String, Object>());
+ protected DynaClass hashMapDynaClass = new LazyDynaMap(new HashMap<String, Object>());
protected DynaClass pojoDynaClass = new WrapDynaBean(new TestBean()).getDynaClass();
protected DynaClass basicDynaClass = new BasicDynaClass("test", BasicDynaBean.class, properties);
@@ -174,15 +175,16 @@
/**
* Test Collection
*/
- public void testCollection(LazyDynaList list, Class testClass, DynaClass testDynaClass, Object wrongBean) {
+ public void testCollection(LazyDynaList list, Class<?> testClass, DynaClass testDynaClass, Object wrongBean) {
// ----- Create Collection & Array of Maps -----
int size = 5;
- List testList = new ArrayList(size);
- TreeMap[] testArray = new TreeMap[size];
+ List<Object> testList = new ArrayList<Object>(size);
+ TreeMap<?, ?>[] testArray = new TreeMap[size];
for (int i = 0; i < size; i++) {
- testArray[i] = new TreeMap();
- testArray[i].put("prop"+i, "val"+i);
+ TreeMap<String, Object> map = new TreeMap<String, Object>();
+ map.put("prop"+i, "val"+i);
+ testArray[i] = map;
testList.add(testArray[i]);
}
@@ -192,7 +194,7 @@
assertEquals("1. check size", size, lazyList.size());
DynaBean[] dynaArray = lazyList.toDynaBeanArray();
- TreeMap[] mapArray = (TreeMap[])lazyList.toArray();
+ TreeMap<?, ?>[] mapArray = (TreeMap[])lazyList.toArray();
// Check values
assertEquals("2. check size", size, dynaArray.length);
@@ -226,13 +228,13 @@
*/
public void testNullType() {
LazyDynaList lazyList = new LazyDynaList();
- lazyList.add(new HashMap());
+ lazyList.add(new HashMap<String, Object>());
}
/**
* Test DynaBean Create
*/
- private void dynaBeanTest(LazyDynaList list, Class testClass, DynaClass testDynaClass, Object wrongBean) {
+ private void dynaBeanTest(LazyDynaList list, Class<?> testClass, DynaClass testDynaClass, Object wrongBean) {
// Test get(index) created correct DynaBean - Second
Object dynaBean = list.get(1);
@@ -276,7 +278,7 @@
}
// Create Collection
- List collection = new ArrayList();
+ List<Object> collection = new ArrayList<Object>();
try {
collection.add(testDynaClass.newInstance());
collection.add(testDynaClass.newInstance());
@@ -339,7 +341,7 @@
/**
* Test Map Create
*/
- private void mapTest(LazyDynaList list, Class testClass, Object wrongBean) {
+ private void mapTest(LazyDynaList list, Class<?> testClass, Object wrongBean) {
// Test get(index) created correct DynaBean - First
Object dynaBean = list.get(0);
@@ -355,7 +357,7 @@
Object array = list.toArray();
assertNotNull("5. Array Not Created", array);
assertEquals("6. Not Map[]", testClass, array.getClass().getComponentType());
- Map[] mapArray = (Map[])array;
+ Map<?, ?>[] mapArray = (Map[])array;
assertEquals("7. Array Size Wrong", 1, mapArray.length);
// Test get(index) created correct DynaBean - Third
@@ -388,7 +390,7 @@
/**
* Test Pojo Create
*/
- private void pojoTest(LazyDynaList list, Class testClass, Object wrongBean) {
+ private void pojoTest(LazyDynaList list, Class<?> testClass, Object wrongBean) {
// Test get(index) created correct DynaBean - First
Object dynaBean = list.get(0);
@@ -568,4 +570,51 @@
}
-}
\ No newline at end of file
+ /**
+ * Tests toArray() if the list contains DynaBean objects.
+ */
+ public void testToArrayDynaBeans() {
+ LazyDynaList list = new LazyDynaList(LazyDynaBean.class);
+ LazyDynaBean elem = new LazyDynaBean();
+ list.add(elem);
+ LazyDynaBean[] beans = new LazyDynaBean[1];
+ assertSame("Wrong array", beans, list.toArray(beans));
+ assertSame("Wrong element", elem, beans[0]);
+ }
+
+ /**
+ * Tests toArray() if the list contains maps.
+ */
+ public void testToArrayMapType() {
+ LazyDynaList list = new LazyDynaList(HashMap.class);
+ HashMap<String, Object> elem = new HashMap<String, Object>();
+ list.add(elem);
+ Map<?, ?>[] array = new Map[1];
+ assertSame("Wrong array", array, list.toArray(array));
+ assertEquals("Wrong element", elem, array[0]);
+ }
+
+ /**
+ * Tests toArray() for other bean elements.
+ */
+ public void testToArrayOtherType() {
+ LazyDynaList list = new LazyDynaList(TestBean.class);
+ TestBean elem = new TestBean();
+ list.add(elem);
+ TestBean[] array = new TestBean[1];
+ assertSame("Wrong array", array, list.toArray(array));
+ assertEquals("Wrong element", elem, array[0]);
+ }
+
+ /**
+ * Tests toArray() if the array's size does not fit the collection size.
+ */
+ public void testToArrayUnsufficientSize() {
+ LazyDynaList list = new LazyDynaList(LazyDynaBean.class);
+ LazyDynaBean elem = new LazyDynaBean();
+ list.add(elem);
+ LazyDynaBean[] array = (LazyDynaBean[]) list.toArray(new LazyDynaBean[0]);
+ assertEquals("Wrong array size", 1, array.length);
+ assertEquals("Wrong element", elem, array[0]);
+ }
+}
diff --git a/src/test/java/org/apache/commons/beanutils/LazyDynaMapTestCase.java b/src/test/java/org/apache/commons/beanutils/LazyDynaMapTestCase.java
index e919b84..1b54d63 100644
--- a/src/test/java/org/apache/commons/beanutils/LazyDynaMapTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/LazyDynaMapTestCase.java
@@ -16,15 +16,16 @@
*/
package org.apache.commons.beanutils;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.TreeMap;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.LinkedList;
import java.lang.reflect.InvocationTargetException;
-import junit.framework.TestCase;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
@@ -160,12 +161,12 @@
dynaMap.set(testProperty, testKey, testInteger1);
assertEquals("Check Mapped Property exists", HashMap.class, dynaMap.get(testProperty).getClass());
assertEquals("Check First Mapped Value is correct(a)", testInteger1, dynaMap.get(testProperty, testKey));
- assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((HashMap)dynaMap.get(testProperty)).get(testKey));
+ assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((HashMap<?, ?>)dynaMap.get(testProperty)).get(testKey));
// Set the property again - should set the new value
dynaMap.set(testProperty, testKey, testInteger2);
assertEquals("Check Second Mapped Value is correct(a)", testInteger2, dynaMap.get(testProperty, testKey));
- assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((HashMap)dynaMap.get(testProperty)).get(testKey));
+ assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((HashMap<?, ?>)dynaMap.get(testProperty)).get(testKey));
}
/**
@@ -187,12 +188,12 @@
dynaMap.set(testProperty, testKey, testInteger1);
assertEquals("Check Mapped Property exists", TreeMap.class, dynaMap.get(testProperty).getClass());
assertEquals("Check First Mapped Value is correct(a)", testInteger1, dynaMap.get(testProperty, testKey));
- assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((TreeMap)dynaMap.get(testProperty)).get(testKey));
+ assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((TreeMap<?, ?>)dynaMap.get(testProperty)).get(testKey));
// Set the property again - should set the new value
dynaMap.set(testProperty, testKey, testInteger2);
assertEquals("Check Second Mapped Value is correct(a)", testInteger2, dynaMap.get(testProperty, testKey));
- assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((TreeMap)dynaMap.get(testProperty)).get(testKey));
+ assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((TreeMap<?, ?>)dynaMap.get(testProperty)).get(testKey));
}
/**
@@ -280,13 +281,13 @@
assertNotNull("Check Indexed Property is not null", dynaMap.get(testProperty));
assertEquals("Check Indexed Property is correct type", ArrayList.class, dynaMap.get(testProperty).getClass());
assertEquals("Check First Indexed Value is correct", testInteger1, dynaMap.get(testProperty, index));
- assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((ArrayList)dynaMap.get(testProperty)).size()));
+ assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((ArrayList<?>)dynaMap.get(testProperty)).size()));
// Set a second indexed value, should automatically grow the ArrayList and set appropriate indexed value
index = index + 2;
dynaMap.set(testProperty, index, testString1);
assertEquals("Check Second Indexed Value is correct", testString1, dynaMap.get(testProperty, index));
- assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((ArrayList)dynaMap.get(testProperty)).size()));
+ assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((ArrayList<?>)dynaMap.get(testProperty)).size()));
}
/**
@@ -310,13 +311,13 @@
dynaMap.set(testProperty, index, testString1);
assertEquals("Check Property type is correct", LinkedList.class, dynaMap.get(testProperty).getClass());
assertEquals("Check First Indexed Value is correct", testString1, dynaMap.get(testProperty, index));
- assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((LinkedList)dynaMap.get(testProperty)).size()));
+ assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((LinkedList<?>)dynaMap.get(testProperty)).size()));
// Set a second indexed value, should automatically grow the LinkedList and set appropriate indexed value
index = index + 2;
dynaMap.set(testProperty, index, testInteger1);
assertEquals("Check Second Indexed Value is correct", testInteger1, dynaMap.get(testProperty, index));
- assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((LinkedList)dynaMap.get(testProperty)).size()));
+ assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((LinkedList<?>)dynaMap.get(testProperty)).size()));
}
/**
@@ -495,16 +496,16 @@
// Create LazyDynaMap using TreeMap
// containing some properties
- LazyDynaMap orig = new LazyDynaMap(new TreeMap());
+ LazyDynaMap orig = new LazyDynaMap(new TreeMap<String, Object>());
orig.set("indexProp", 0, "indexVal0");
orig.set("indexProp", 1, "indexVal1");
- assertEquals("Index prop size", 2, ((List)orig.get("indexProp")).size());
+ assertEquals("Index prop size", 2, ((List<?>)orig.get("indexProp")).size());
LazyDynaMap newOne = (LazyDynaMap)orig.newInstance();
- Map newMap = newOne.getMap();
+ Map<String, Object> newMap = newOne.getMap();
assertEquals("Check Map type", TreeMap.class, newMap.getClass());
- ArrayList indexProp = (ArrayList)newMap.get("indexProp");
+ ArrayList<?> indexProp = (ArrayList<?>)newMap.get("indexProp");
assertNotNull("Indexed Prop missing", indexProp);
assertEquals("Index prop size", 0, indexProp.size());
}
diff --git a/src/test/java/org/apache/commons/beanutils/MappedPropertyTestBean.java b/src/test/java/org/apache/commons/beanutils/MappedPropertyTestBean.java
index e4358a6..fa0ca02 100644
--- a/src/test/java/org/apache/commons/beanutils/MappedPropertyTestBean.java
+++ b/src/test/java/org/apache/commons/beanutils/MappedPropertyTestBean.java
@@ -29,8 +29,8 @@
public class MappedPropertyTestBean {
- private final Map map = new HashMap();
- private final Map myMap = new HashMap();
+ private final Map<Object, Object> map = new HashMap<Object, Object>();
+ private final Map<Object, Object> myMap = new HashMap<Object, Object>();
// -------------------------------------------------------------- Properties
@@ -78,7 +78,7 @@
public String getInvalidGetter(String key, String other) {
return (String) map.get(key);
}
- public Map getMyMap() {
+ public Map<Object, Object> getMyMap() {
return myMap;
}
diff --git a/src/test/java/org/apache/commons/beanutils/MappedPropertyTestCase.java b/src/test/java/org/apache/commons/beanutils/MappedPropertyTestCase.java
index 77e5906..f7e8531 100644
--- a/src/test/java/org/apache/commons/beanutils/MappedPropertyTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/MappedPropertyTestCase.java
@@ -16,11 +16,9 @@
*/
package org.apache.commons.beanutils;
-import junit.framework.TestCase;
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
/**
* <p>Test Case for the <code>MappedPropertyDescriptor</code>.</p>
@@ -29,9 +27,6 @@
*/
public class MappedPropertyTestCase extends TestCase {
- private static final Log log = LogFactory.getLog(MappedPropertyTestCase.class);
-
-
// ---------------------------------------------------------- Constructors
/**
@@ -80,7 +75,7 @@
*/
public void testFound() {
String property = "mapproperty";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -96,7 +91,7 @@
*/
public void testBooleanMapped() {
String property = "mappedBoolean";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -112,10 +107,9 @@
*/
public void testNotFound() {
String property = "xxxxxxx";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
- MappedPropertyDescriptor desc
- = new MappedPropertyDescriptor(property, clazz);
+ new MappedPropertyDescriptor(property, clazz);
fail("Property '" + property + "' found in " + clazz.getName());
} catch (Exception ex) {
// expected result
@@ -127,7 +121,7 @@
*/
public void testMappedGetterOnly() {
String property = "mappedGetterOnly";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -143,7 +137,7 @@
*/
public void testMappedSetterOnly() {
String property = "mappedSetterOnly";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -159,7 +153,7 @@
*/
public void testInvalidSetter() {
String property = "invalidSetter";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -175,7 +169,7 @@
*/
public void testInvalidGetter() {
String property = "invalidGetter";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -195,7 +189,7 @@
*/
public void testDifferentTypes() {
String property = "differentTypes";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -207,12 +201,10 @@
}
/**
- * Test Mpa getter
+ * Test Map getter
*/
public void testMapGetter() {
MappedPropertyTestBean bean = new MappedPropertyTestBean();
- Class clazz = MappedPropertyTestBean.class;
- String property = "myMap";
try {
String testValue = "test value";
String testKey = "testKey";
@@ -229,7 +221,7 @@
*/
public void testAnyArgsProperty() {
String property = "anyMapped";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -241,11 +233,11 @@
}
/**
- * Test property with two primitve args
+ * Test property with two primitive args
*/
public void testPrimitiveArgsProperty() {
String property = "mappedPrimitive";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -261,10 +253,9 @@
*/
public void testProtected() {
String property = "protectedProperty";
- Class clazz = MappedPropertyTestBean.class;
+ Class<?> clazz = MappedPropertyTestBean.class;
try {
- MappedPropertyDescriptor desc
- = new MappedPropertyDescriptor(property, clazz);
+ new MappedPropertyDescriptor(property, clazz);
fail("Property '" + property + "' found in " + clazz.getName());
} catch (Exception ex) {
// expected result
@@ -277,7 +268,7 @@
*/
public void testPublicParentMethod() {
String property = "mapproperty";
- Class clazz = MappedPropertyChildBean.class;
+ Class<?> clazz = MappedPropertyChildBean.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -293,10 +284,9 @@
*/
public void testProtectedParentMethod() {
String property = "protectedMapped";
- Class clazz = MappedPropertyChildBean.class;
+ Class<?> clazz = MappedPropertyChildBean.class;
try {
- MappedPropertyDescriptor desc
- = new MappedPropertyDescriptor(property, clazz);
+ new MappedPropertyDescriptor(property, clazz);
fail("Property '" + property + "' found in " + clazz.getName());
} catch (Exception ex) {
}
@@ -308,7 +298,7 @@
*/
public void testInterfaceMapped() {
String property = "mapproperty";
- Class clazz = MappedPropertyTestInterface.class;
+ Class<?> clazz = MappedPropertyTestInterface.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
@@ -324,10 +314,9 @@
*/
public void testInterfaceNotFound() {
String property = "XXXXXX";
- Class clazz = MappedPropertyTestInterface.class;
+ Class<?> clazz = MappedPropertyTestInterface.class;
try {
- MappedPropertyDescriptor desc
- = new MappedPropertyDescriptor(property, clazz);
+ new MappedPropertyDescriptor(property, clazz);
fail("Property '" + property + "' found in " + clazz.getName());
} catch (Exception ex) {
}
@@ -338,7 +327,7 @@
*/
public void testChildInterfaceMapped() {
String property = "mapproperty";
- Class clazz = MappedPropertyChildInterface.class;
+ Class<?> clazz = MappedPropertyChildInterface.class;
try {
MappedPropertyDescriptor desc
= new MappedPropertyDescriptor(property, clazz);
diff --git a/src/test/java/org/apache/commons/beanutils/PropertyUtilsBenchCase.java b/src/test/java/org/apache/commons/beanutils/PropertyUtilsBenchCase.java
index 43871b2..4e61729 100644
--- a/src/test/java/org/apache/commons/beanutils/PropertyUtilsBenchCase.java
+++ b/src/test/java/org/apache/commons/beanutils/PropertyUtilsBenchCase.java
@@ -20,10 +20,10 @@
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
-import junit.framework.TestCase;
+
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
@@ -63,7 +63,7 @@
// Input objects that have identical sets of properties and values.
private BenchBean inBean = null;
private DynaBean inDyna = null;
- private Map inMap = null;
+ private Map<String, Object> inMap = null;
// Output objects that have identical sets of properties.
private BenchBean outBean = null;
@@ -104,7 +104,7 @@
// Create input instances
inBean = new BenchBean();
- inMap = new HashMap();
+ inMap = new HashMap<String, Object>();
inMap.put("booleanProperty", new Boolean(inBean.getBooleanProperty()));
inMap.put("byteProperty", new Byte(inBean.getByteProperty()));
inMap.put("doubleProperty", new Double(inBean.getDoubleProperty()));
@@ -114,19 +114,16 @@
inMap.put("shortProperty", new Short(inBean.getShortProperty()));
inMap.put("stringProperty", inBean.getStringProperty());
inDyna = dynaClass.newInstance();
- Iterator inKeys = inMap.keySet().iterator();
- while (inKeys.hasNext()) {
- String inKey = (String) inKeys.next();
- inDyna.set(inKey, inMap.get(inKey));
+ for (Map.Entry<String, Object> e : inMap.entrySet()) {
+ inDyna.set(e.getKey(), e.getValue());
}
// Create output instances
outBean = new BenchBean();
outDyna = dynaClass.newInstance();
- Iterator outKeys = inMap.keySet().iterator();
- while (outKeys.hasNext()) {
- String outKey = (String) outKeys.next();
- outDyna.set(outKey, inMap.get(outKey));
+ inDyna = dynaClass.newInstance();
+ for (Map.Entry<String, Object> e : inMap.entrySet()) {
+ outDyna.set(e.getKey(), e.getValue());
}
// Set up PropertyUtilsBean instance we will use
diff --git a/src/test/java/org/apache/commons/beanutils/PropertyUtilsTestCase.java b/src/test/java/org/apache/commons/beanutils/PropertyUtilsTestCase.java
index bf78e43..2e9e3ea 100644
--- a/src/test/java/org/apache/commons/beanutils/PropertyUtilsTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/PropertyUtilsTestCase.java
@@ -253,7 +253,7 @@
*/
public void testCopyPropertiesMap() {
- Map map = new HashMap();
+ Map<String, Object> map = new HashMap<String, Object>();
map.put("booleanProperty", Boolean.FALSE);
map.put("doubleProperty", new Double(333.0));
map.put("dupProperty", new String[] { "New 0", "New 1", "New 2" });
@@ -308,7 +308,7 @@
*/
public void testDescribe() {
- Map map = null;
+ Map<String, Object> map = null;
try {
map = PropertyUtils.describe(bean);
} catch (Exception e) {
@@ -1044,7 +1044,7 @@
public void testGetIndexedList() {
String[] firstArray = new String[] {"FIRST-1", "FIRST-2", "FIRST-3"};
String[] secondArray = new String[] {"SECOND-1", "SECOND-2", "SECOND-3", "SECOND-4"};
- List mainList = new ArrayList();
+ List<Object> mainList = new ArrayList<Object>();
mainList.add(Arrays.asList(firstArray));
mainList.add(Arrays.asList(secondArray));
TestBean bean = new TestBean(mainList);
@@ -1065,14 +1065,14 @@
* Test getting a value out of a mapped Map
*/
public void testGetIndexedMap() {
- Map firstMap = new HashMap();
+ Map<String, Object> firstMap = new HashMap<String, Object>();
firstMap.put("FIRST-KEY-1", "FIRST-VALUE-1");
firstMap.put("FIRST-KEY-2", "FIRST-VALUE-2");
- Map secondMap = new HashMap();
+ Map<String, Object> secondMap = new HashMap<String, Object>();
secondMap.put("SECOND-KEY-1", "SECOND-VALUE-1");
secondMap.put("SECOND-KEY-2", "SECOND-VALUE-2");
- List mainList = new ArrayList();
+ List<Object> mainList = new ArrayList<Object>();
mainList.add(firstMap);
mainList.add(secondMap);
TestBean bean = new TestBean(mainList);
@@ -1174,7 +1174,7 @@
*/
public void testGetMappedList() {
TestBean bean = new TestBean();
- List list = new ArrayList();
+ List<Object> list = new ArrayList<Object>();
list.add("klm");
list.add("nop");
list.add("qrs");
@@ -1193,7 +1193,7 @@
*/
public void testGetMappedMap() {
TestBean bean = new TestBean();
- Map map = new HashMap();
+ Map<String, Object> map = new HashMap<String, Object>();
map.put("sub-key-1", "sub-value-1");
map.put("sub-key-2", "sub-value-2");
map.put("sub-key-3", "sub-value-3");
@@ -1669,7 +1669,7 @@
// don't init!
try {
- NestedTestBean value = (NestedTestBean) PropertyUtils.getProperty(
+ PropertyUtils.getProperty(
nestedBean,
"simpleBeanProperty.indexedProperty[0]");
fail("NestedNullException not thrown");
@@ -1704,7 +1704,7 @@
*/
public void testGetPropertyType() {
- Class clazz = null;
+ Class<?> clazz = null;
int intArray[] = new int[0];
String stringArray[] = new String[0];
@@ -1906,9 +1906,8 @@
assertTrue("Found foo descriptor", n >= 0);
Method reader = pd[n].getReadMethod();
assertNotNull("Found foo read method", reader);
- Object value = null;
try {
- value = reader.invoke(beanPrivate, new Class[0]);
+ reader.invoke(beanPrivate, (Object[]) new Class<?>[0]);
fail("Foo reader did throw IllegalAccessException");
} catch (IllegalAccessException e) {
// Expected result for this test
@@ -2043,9 +2042,8 @@
*/
public void testGetSimpleIndexed() {
- Object value = null;
try {
- value = PropertyUtils.getSimpleProperty(bean,
+ PropertyUtils.getSimpleProperty(bean,
"intIndexed[0]");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalAccessException e) {
@@ -2120,9 +2118,8 @@
*/
public void testGetSimpleNested() {
- Object value = null;
try {
- value = PropertyUtils.getSimpleProperty(bean,
+ PropertyUtils.getSimpleProperty(bean,
"nested.stringProperty");
fail("Should have thrown IllegaArgumentException");
} catch (IllegalAccessException e) {
@@ -2616,45 +2613,45 @@
public void testSetIndexedList() {
String[] firstArray = new String[] {"FIRST-1", "FIRST-2", "FIRST-3"};
String[] secondArray = new String[] {"SECOND-1", "SECOND-2", "SECOND-3", "SECOND-4"};
- List mainList = new ArrayList();
+ List<Object> mainList = new ArrayList<Object>();
mainList.add(Arrays.asList(firstArray));
mainList.add(Arrays.asList(secondArray));
TestBean bean = new TestBean(mainList);
- assertEquals("BEFORE", "SECOND-4", ((List)bean.getListIndexed().get(1)).get(3));
+ assertEquals("BEFORE", "SECOND-4", ((List<?>)bean.getListIndexed().get(1)).get(3));
try {
PropertyUtils.setProperty(bean, "listIndexed[1][3]", "SECOND-4-UPDATED");
} catch (Throwable t) {
fail("Threw " + t + "");
}
- assertEquals("AFTER", "SECOND-4-UPDATED", ((List)bean.getListIndexed().get(1)).get(3));
+ assertEquals("AFTER", "SECOND-4-UPDATED", ((List<?>)bean.getListIndexed().get(1)).get(3));
}
/**
* Test setting a value out of a mapped Map
*/
public void testSetIndexedMap() {
- Map firstMap = new HashMap();
+ Map<String, Object> firstMap = new HashMap<String, Object>();
firstMap.put("FIRST-KEY-1", "FIRST-VALUE-1");
firstMap.put("FIRST-KEY-2", "FIRST-VALUE-2");
- Map secondMap = new HashMap();
+ Map<String, Object> secondMap = new HashMap<String, Object>();
secondMap.put("SECOND-KEY-1", "SECOND-VALUE-1");
secondMap.put("SECOND-KEY-2", "SECOND-VALUE-2");
- List mainList = new ArrayList();
+ List<Object> mainList = new ArrayList<Object>();
mainList.add(firstMap);
mainList.add(secondMap);
TestBean bean = new TestBean(mainList);
- assertEquals("BEFORE", null, ((Map)bean.getListIndexed().get(0)).get("FIRST-NEW-KEY"));
- assertEquals("BEFORE", "SECOND-VALUE-1", ((Map)bean.getListIndexed().get(1)).get("SECOND-KEY-1"));
+ assertEquals("BEFORE", null, ((Map<?, ?>)bean.getListIndexed().get(0)).get("FIRST-NEW-KEY"));
+ assertEquals("BEFORE", "SECOND-VALUE-1", ((Map<?, ?>)bean.getListIndexed().get(1)).get("SECOND-KEY-1"));
try {
PropertyUtils.setProperty(bean, "listIndexed[0](FIRST-NEW-KEY)", "FIRST-NEW-VALUE");
PropertyUtils.setProperty(bean, "listIndexed[1](SECOND-KEY-1)", "SECOND-VALUE-1-UPDATED");
} catch (Throwable t) {
fail("Threw " + t + "");
}
- assertEquals("BEFORE", "FIRST-NEW-VALUE", ((Map)bean.getListIndexed().get(0)).get("FIRST-NEW-KEY"));
- assertEquals("AFTER", "SECOND-VALUE-1-UPDATED", ((Map)bean.getListIndexed().get(1)).get("SECOND-KEY-1"));
+ assertEquals("BEFORE", "FIRST-NEW-VALUE", ((Map<?, ?>)bean.getListIndexed().get(0)).get("FIRST-NEW-KEY"));
+ assertEquals("AFTER", "SECOND-VALUE-1-UPDATED", ((Map<?, ?>)bean.getListIndexed().get(1)).get("SECOND-KEY-1"));
}
@@ -3093,19 +3090,19 @@
*/
public void testSetMappedList() {
TestBean bean = new TestBean();
- List list = new ArrayList();
+ List<Object> list = new ArrayList<Object>();
list.add("klm");
list.add("nop");
list.add("qrs");
bean.getMapProperty().put("mappedList", list);
- assertEquals("BEFORE", "klm", ((List)bean.getMapProperty().get("mappedList")).get(0));
+ assertEquals("BEFORE", "klm", ((List<?>)bean.getMapProperty().get("mappedList")).get(0));
try {
PropertyUtils.setProperty(bean, "mapProperty(mappedList)[0]", "KLM-UPDATED");
} catch (Throwable t) {
fail("Threw " + t + "");
}
- assertEquals("AFTER", "KLM-UPDATED", ((List)bean.getMapProperty().get("mappedList")).get(0));
+ assertEquals("AFTER", "KLM-UPDATED", ((List<?>)bean.getMapProperty().get("mappedList")).get(0));
}
/**
@@ -3113,19 +3110,19 @@
*/
public void testSetMappedMap() {
TestBean bean = new TestBean();
- Map map = new HashMap();
+ Map<String, Object> map = new HashMap<String, Object>();
map.put("sub-key-1", "sub-value-1");
map.put("sub-key-2", "sub-value-2");
map.put("sub-key-3", "sub-value-3");
bean.getMapProperty().put("mappedMap", map);
- assertEquals("BEFORE", "sub-value-3", ((Map)bean.getMapProperty().get("mappedMap")).get("sub-key-3"));
+ assertEquals("BEFORE", "sub-value-3", ((Map<?, ?>)bean.getMapProperty().get("mappedMap")).get("sub-key-3"));
try {
PropertyUtils.setProperty(bean, "mapProperty(mappedMap)(sub-key-3)", "SUB-KEY-3-UPDATED");
} catch (Throwable t) {
fail("Threw " + t + "");
}
- assertEquals("AFTER", "SUB-KEY-3-UPDATED", ((Map)bean.getMapProperty().get("mappedMap")).get("sub-key-3"));
+ assertEquals("AFTER", "SUB-KEY-3-UPDATED", ((Map<?, ?>)bean.getMapProperty().get("mappedMap")).get("sub-key-3"));
}
/**
@@ -4011,7 +4008,7 @@
Method reader = PropertyUtils.getReadMethod(pd[n]);
assertNotNull("Reader for " + properties[i],
reader);
- Class clazz = reader.getDeclaringClass();
+ Class<?> clazz = reader.getDeclaringClass();
assertNotNull("Declaring class for " + properties[i],
clazz);
assertEquals("Correct declaring class for " + properties[i],
@@ -4020,7 +4017,7 @@
// Actually call the reader method we received
try {
- reader.invoke(bean, new Class[0]);
+ reader.invoke(bean, (Object[]) new Class<?>[0]);
} catch (Throwable t) {
fail("Call for " + properties[i] + ": " + t);
}
@@ -4070,7 +4067,7 @@
Method writer = PropertyUtils.getWriteMethod(pd[n]);
assertNotNull("Writer for " + properties[i],
writer);
- Class clazz = writer.getDeclaringClass();
+ Class<?> clazz = writer.getDeclaringClass();
assertNotNull("Declaring class for " + properties[i],
clazz);
assertEquals("Correct declaring class for " + properties[i],
@@ -4208,9 +4205,6 @@
assertEquals("Cannot set no-getter property", "Omega", bean.getSecret());
// test mapped no getter descriptor
- MappedPropertyDescriptor descriptor
- = new MappedPropertyDescriptor("noGetterMappedProperty", BetaBean.class);
-
assertNotNull("Map Descriptor is null", PropertyUtils.getPropertyDescriptor(bean, "noGetterMappedProperty"));
PropertyUtils.setMappedProperty(bean, "noGetterMappedProperty", "Epsilon", "Epsilon");
@@ -4268,8 +4262,8 @@
* mistake.
*/
public void testNestedPropertyKeyOrIndexOnBeanImplementingMap() throws Exception {
- HashMap map = new HashMap();
- HashMap submap = new HashMap();
+ HashMap<String, Object> map = new HashMap<String, Object>();
+ HashMap<String, Object> submap = new HashMap<String, Object>();
BetaBean betaBean1 = new BetaBean("test1");
BetaBean betaBean2 = new BetaBean("test2");
@@ -4312,7 +4306,7 @@
// However this isn't how javabeans property methods work. A map
// only effectively has "simple" properties, even when the
// returned object is a Map or Array.
- Object o = PropertyUtils.getNestedProperty(map, "submap[3]");
+ PropertyUtils.getNestedProperty(map, "submap[3]");
// What, no exception? In that case, getNestedProperties has
// probably just tried to do
@@ -4336,10 +4330,10 @@
* <p>
* If there are no keys, an empty string is returned.
*/
- private String keysToString(Map map) {
+ private String keysToString(Map<?, ?> map) {
Object[] mapKeys = map.keySet().toArray();
java.util.Arrays.sort(mapKeys);
- StringBuffer buf = new StringBuffer();
+ StringBuilder buf = new StringBuilder();
for(int i=0; i<mapKeys.length; ++i) {
if (i != 0)
buf.append(", ");
@@ -4416,7 +4410,7 @@
assertEquals("setNestedProperty on non-simple property failed",
"value1", utilsBean.getNestedProperty(bean, "mapProperty"));
- HashMap myMap = new HashMap();
+ HashMap<String, Object> myMap = new HashMap<String, Object>();
myMap.put("thebean", bean);
utilsBean.getNestedProperty(myMap, "thebean.mapitem");
utilsBean.getNestedProperty(myMap, "thebean(mapitem)");
diff --git a/src/test/java/org/apache/commons/beanutils/PropsFirstPropertyUtilsBean.java b/src/test/java/org/apache/commons/beanutils/PropsFirstPropertyUtilsBean.java
index 30f3bd6..62e23e7 100644
--- a/src/test/java/org/apache/commons/beanutils/PropsFirstPropertyUtilsBean.java
+++ b/src/test/java/org/apache/commons/beanutils/PropsFirstPropertyUtilsBean.java
@@ -16,9 +16,9 @@
*/
package org.apache.commons.beanutils;
-import java.util.Map;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
+import java.util.Map;
/**
* A PropertyUtilsBean which customises the behaviour of the
@@ -40,7 +40,7 @@
* be correctly handled.
*/
@Override
- protected Object getPropertyOfMapBean(Map bean, String propertyName)
+ protected Object getPropertyOfMapBean(Map<?, ?> bean, String propertyName)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
PropertyDescriptor descriptor = getPropertyDescriptor(bean, propertyName);
@@ -60,7 +60,7 @@
* be correctly handled.
*/
@Override
- protected void setPropertyOfMapBean(Map bean, String propertyName, Object value)
+ protected void setPropertyOfMapBean(Map<String, Object> bean, String propertyName, Object value)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
PropertyDescriptor descriptor = getPropertyDescriptor(bean, propertyName);
if (descriptor == null) {
diff --git a/src/test/java/org/apache/commons/beanutils/TestBean.java b/src/test/java/org/apache/commons/beanutils/TestBean.java
index 76b8b21..a6bc3ef 100644
--- a/src/test/java/org/apache/commons/beanutils/TestBean.java
+++ b/src/test/java/org/apache/commons/beanutils/TestBean.java
@@ -19,11 +19,11 @@
package org.apache.commons.beanutils;
+import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.io.Serializable;
/**
@@ -93,7 +93,7 @@
setStringProperty(stringProperty);
}
- public TestBean(List listIndexed) {
+ public TestBean(List<Object> listIndexed) {
this.listIndexed = listIndexed;
}
@@ -269,9 +269,9 @@
/**
* A List property accessed as an indexed property.
*/
- private List listIndexed = new ArrayList();
+ private List<Object> listIndexed = new ArrayList<Object>();
- public List getListIndexed() {
+ public List<Object> getListIndexed() {
return (listIndexed);
}
@@ -293,22 +293,22 @@
/**
* A mapped property with only a getter and setter for a Map.
*/
- private Map mapProperty = null;
+ private Map<String, Object> mapProperty = null;
- public Map getMapProperty() {
+ public Map<String, Object> getMapProperty() {
// Create the map the very first time
if (mapProperty == null) {
- mapProperty = new HashMap();
+ mapProperty = new HashMap<String, Object>();
mapProperty.put("First Key", "First Value");
mapProperty.put("Second Key", "Second Value");
}
return (mapProperty);
}
- public void setMapProperty(Map mapProperty) {
+ public void setMapProperty(Map<String, Object> mapProperty) {
// Create the map the very first time
if (mapProperty == null) {
- mapProperty = new HashMap();
+ mapProperty = new HashMap<String, Object>();
mapProperty.put("First Key", "First Value");
mapProperty.put("Second Key", "Second Value");
}
@@ -319,12 +319,12 @@
/**
* A mapped property that has String keys and Object values.
*/
- private HashMap mappedObjects = null;
+ private HashMap<String, Object> mappedObjects = null;
public Object getMappedObjects(String key) {
// Create the map the very first time
if (mappedObjects == null) {
- mappedObjects = new HashMap();
+ mappedObjects = new HashMap<String, Object>();
mappedObjects.put("First Key", "First Value");
mappedObjects.put("Second Key", "Second Value");
}
@@ -334,7 +334,7 @@
public void setMappedObjects(String key, Object value) {
// Create the map the very first time
if (mappedObjects == null) {
- mappedObjects = new HashMap();
+ mappedObjects = new HashMap<String, Object>();
mappedObjects.put("First Key", "First Value");
mappedObjects.put("Second Key", "Second Value");
}
@@ -345,22 +345,22 @@
/**
* A mapped property that has String keys and String values.
*/
- private HashMap mappedProperty = null;
+ private HashMap<String, String> mappedProperty = null;
public String getMappedProperty(String key) {
// Create the map the very first time
if (mappedProperty == null) {
- mappedProperty = new HashMap();
+ mappedProperty = new HashMap<String, String>();
mappedProperty.put("First Key", "First Value");
mappedProperty.put("Second Key", "Second Value");
}
- return ((String) mappedProperty.get(key));
+ return (mappedProperty.get(key));
}
public void setMappedProperty(String key, String value) {
// Create the map the very first time
if (mappedProperty == null) {
- mappedProperty = new HashMap();
+ mappedProperty = new HashMap<String, String>();
mappedProperty.put("First Key", "First Value");
mappedProperty.put("Second Key", "Second Value");
}
@@ -371,21 +371,21 @@
/**
* A mapped property that has String keys and int values.
*/
- private HashMap mappedIntProperty = null;
+ private HashMap<String, Integer> mappedIntProperty = null;
public int getMappedIntProperty(String key) {
// Create the map the very first time
if (mappedIntProperty == null) {
- mappedIntProperty = new HashMap();
- mappedIntProperty.put("One", new Integer(1));
- mappedIntProperty.put("Two", new Integer(2));
+ mappedIntProperty = new HashMap<String, Integer>();
+ mappedIntProperty.put("One", 1);
+ mappedIntProperty.put("Two", 2);
}
- Integer x = (Integer) mappedIntProperty.get(key);
+ Integer x = mappedIntProperty.get(key);
return ((x == null) ? 0 : x.intValue());
}
public void setMappedIntProperty(String key, int value) {
- mappedIntProperty.put(key, new Integer(value));
+ mappedIntProperty.put(key, value);
}
diff --git a/src/test/java/org/apache/commons/beanutils/TestResultSet.java b/src/test/java/org/apache/commons/beanutils/TestResultSet.java
index 1c2f728..733a80c 100644
--- a/src/test/java/org/apache/commons/beanutils/TestResultSet.java
+++ b/src/test/java/org/apache/commons/beanutils/TestResultSet.java
@@ -88,7 +88,7 @@
*/
public static ResultSet createProxy(InvocationHandler invocationHandler) {
ClassLoader classLoader = ResultSet.class.getClassLoader();
- Class[] interfaces = new Class[] { ResultSet.class };
+ Class<?>[] interfaces = new Class[] { ResultSet.class };
return (ResultSet)Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
}
@@ -472,12 +472,12 @@
}
- public Object getObject(int columnIndex, Map map) throws SQLException {
+ public Object getObject(int columnIndex, Map<?, ?> map) throws SQLException {
throw new UnsupportedOperationException();
}
- public Object getObject(String columnName, Map map) throws SQLException {
+ public Object getObject(String columnName, Map<?, ?> map) throws SQLException {
throw new UnsupportedOperationException();
}
diff --git a/src/test/java/org/apache/commons/beanutils/TestResultSetMetaData.java b/src/test/java/org/apache/commons/beanutils/TestResultSetMetaData.java
index 9cf7dd2..6d7b2a6 100644
--- a/src/test/java/org/apache/commons/beanutils/TestResultSetMetaData.java
+++ b/src/test/java/org/apache/commons/beanutils/TestResultSetMetaData.java
@@ -77,7 +77,7 @@
*/
public static ResultSetMetaData createProxy(InvocationHandler invocationHandler) {
ClassLoader classLoader = ResultSetMetaData.class.getClassLoader();
- Class[] interfaces = new Class[] { ResultSetMetaData.class };
+ Class<?>[] interfaces = new Class[] { ResultSetMetaData.class };
return (ResultSetMetaData)Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
}
diff --git a/src/test/java/org/apache/commons/beanutils/ThrowExceptionConverter.java b/src/test/java/org/apache/commons/beanutils/ThrowExceptionConverter.java
index ef7be6d..69b6b10 100644
--- a/src/test/java/org/apache/commons/beanutils/ThrowExceptionConverter.java
+++ b/src/test/java/org/apache/commons/beanutils/ThrowExceptionConverter.java
@@ -30,7 +30,7 @@
public class ThrowExceptionConverter implements Converter {
- public Object convert(Class type, Object value) {
+ public <T> T convert(Class<T> type, Object value) {
throw new PassTestException();
}
}
diff --git a/src/test/java/org/apache/commons/beanutils/WrapDynaBeanTestCase.java b/src/test/java/org/apache/commons/beanutils/WrapDynaBeanTestCase.java
index 171d4df..09bc637 100644
--- a/src/test/java/org/apache/commons/beanutils/WrapDynaBeanTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/WrapDynaBeanTestCase.java
@@ -22,6 +22,7 @@
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
+
import junit.framework.Test;
import junit.framework.TestSuite;
@@ -101,7 +102,7 @@
// Invalid getter
try {
- Object result = bean.get("invalidProperty");
+ bean.get("invalidProperty");
fail("Invalid get should have thrown IllegalArgumentException");
} catch (IllegalArgumentException t) {
// Expected result
@@ -141,7 +142,7 @@
// Invalid getter
try {
- Object result = bean.get("invalidProperty", 0);
+ bean.get("invalidProperty", 0);
fail("Invalid get should have thrown IllegalArgumentException");
} catch (IllegalArgumentException t) {
// Expected result
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/Jira157TestCase.java b/src/test/java/org/apache/commons/beanutils/bugs/Jira157TestCase.java
index 1f24417..e1ea177 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/Jira157TestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/Jira157TestCase.java
@@ -94,14 +94,18 @@
*/
public void testIssue_BEANUTILS_157_BeanUtils_Describe_Serializable() {
Object bean = new Serializable() {
+ private static final long serialVersionUID = 1L;
+
+ @SuppressWarnings("unused")
public String getX() {
return "x-value";
}
+ @SuppressWarnings("unused")
public String getY() {
return "y-value";
}
};
- Map result = null;
+ Map<String, String> result = null;
try {
result = BeanUtils.describe(bean);
} catch (Throwable t) {
@@ -127,7 +131,7 @@
return "y-value";
}
};
- Map result = null;
+ Map<String, String> result = null;
try {
result = BeanUtils.describe(bean);
} catch (Throwable t) {
@@ -150,7 +154,7 @@
*/
public void testIssue_BEANUTILS_157_BeanUtils_Describe_Bean() {
Object bean = new FooBar();
- Map result = null;
+ Map<String, String> result = null;
try {
result = BeanUtils.describe(bean);
} catch (Throwable t) {
@@ -172,6 +176,7 @@
String getPackageFoo() {
return "Package Value";
}
+ @SuppressWarnings("unused")
private String getPrivateFoo() {
return "PrivateFoo Value";
}
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/Jira298TestCase.java b/src/test/java/org/apache/commons/beanutils/bugs/Jira298TestCase.java
index 323e2fb..a31cc7b 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/Jira298TestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/Jira298TestCase.java
@@ -122,7 +122,7 @@
Object result = null;
try {
Method m2 = MethodUtils.getAccessibleMethod(bean.getClass(), "getName", new Class[0]);
- result = m2.invoke(bean, null);
+ result = m2.invoke(bean);
} catch (Throwable t) {
log.error("Failed: " + t.getMessage(), t);
fail("Threw exception: " + t);
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/Jira339TestCase.java b/src/test/java/org/apache/commons/beanutils/bugs/Jira339TestCase.java
index a2527b1..cf08c1f 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/Jira339TestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/Jira339TestCase.java
@@ -106,7 +106,7 @@
TestBean bean = new TestBean();
try {
- Map properties = new HashMap();
+ Map<String, Object> properties = new HashMap<String, Object>();
properties.put("comparator", null);
BeanUtils.populate(bean, properties);
} catch (Throwable t) {
@@ -120,14 +120,14 @@
* Test Bean.
*/
public static class TestBean {
- private Comparator comparator;
+ private Comparator<?> comparator;
/**
* Return the comparator.
*
* @return the comparator
*/
- public Comparator getComparator() {
+ public Comparator<?> getComparator() {
return comparator;
}
@@ -136,7 +136,7 @@
*
* @param comparator the comparator
*/
- public void setComparator(Comparator comparator) {
+ public void setComparator(Comparator<?> comparator) {
this.comparator = comparator;
}
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/Jira347TestCase.java b/src/test/java/org/apache/commons/beanutils/bugs/Jira347TestCase.java
index 4f1b815..ae39edf 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/Jira347TestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/Jira347TestCase.java
@@ -22,6 +22,7 @@
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
+import java.util.ArrayList;
import junit.framework.TestCase;
@@ -51,8 +52,8 @@
public void testMappedPropertyDescriptor_AnyArgsProperty() throws Exception {
String className = "org.apache.commons.beanutils.MappedPropertyTestBean";
ClassLoader loader = newClassLoader();
- Class beanClass = loader.loadClass(className);
- Object bean = beanClass.newInstance();
+ Class<?> beanClass = loader.loadClass(className);
+ beanClass.newInstance();
// -----------------------------------------------------------------------------
// Sanity checks only
@@ -102,10 +103,10 @@
*/
private void forceGarbageCollection() throws Exception {
// Fill up memory
- SoftReference ref = new SoftReference(new Object());
+ SoftReference<Object> ref = new SoftReference<Object>(new Object());
int count = 0;
while(ref.get() != null && count++ < 5) {
- java.util.ArrayList list = new java.util.ArrayList();
+ ArrayList<Object> list = new ArrayList<Object>();
try {
long i = 0;
while (true && ref.get() != null) {
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/Jira357TestCase.java b/src/test/java/org/apache/commons/beanutils/bugs/Jira357TestCase.java
index fc0dd2d..75dcdc3 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/Jira357TestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/Jira357TestCase.java
@@ -105,7 +105,7 @@
/**
* Test {@link PropertyUtils#getPropertyDescriptors(Class)}
*/
- private void checkReadMethod(String propertyName, Class expectedDeclaringClass) throws Exception {
+ private void checkReadMethod(String propertyName, Class<?> expectedDeclaringClass) throws Exception {
PropertyDescriptor[] descriptors = null;
try {
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/Jira381TestCase.java b/src/test/java/org/apache/commons/beanutils/bugs/Jira381TestCase.java
index a18b6c5..3c7508b 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/Jira381TestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/Jira381TestCase.java
@@ -48,9 +48,9 @@
*/
public void testIssue_BEANUTILS_381_getMatchingAccessibleMethod() {
- Class target = TestServiceBean.class;
+ Class<?> target = TestServiceBean.class;
String methodName = "performOp";
- Class[] runtimeClasses = new Class[]{TestObjectSubclass.class};
+ Class<?>[] runtimeClasses = new Class<?>[]{TestObjectSubclass.class};
Method returned = MethodUtils.getMatchingAccessibleMethod(target, methodName, runtimeClasses);
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/Jira422TestCase.java b/src/test/java/org/apache/commons/beanutils/bugs/Jira422TestCase.java
index 7904ab7..47973fe 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/Jira422TestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/Jira422TestCase.java
@@ -32,18 +32,19 @@
public void testRootBean() throws Exception {
RootBean bean = new FirstChildBean();
- Class propertyType = PropertyUtils.getPropertyType(bean, "file[0]");
+ Class<?> propertyType = PropertyUtils.getPropertyType(bean, "file[0]");
assertEquals(String.class.getName(), propertyType.getName());
}
public void testSecondChildBean() throws Exception {
RootBean bean = new SecondChildBean();
- Class propertyType = PropertyUtils.getPropertyType(bean, "file[0]");
+ Class<?> propertyType = PropertyUtils.getPropertyType(bean, "file[0]");
assertEquals(String.class.getName(), propertyType.getName());
}
}
+@SuppressWarnings("rawtypes")
class RootBean {
private List file;
@@ -60,6 +61,7 @@
return (String) file.get(i);
}
+ @SuppressWarnings("unchecked")
public void setFile(int i, String file) {
this.file.set(i, file);
}
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/Jira61TestCase.java b/src/test/java/org/apache/commons/beanutils/bugs/Jira61TestCase.java
index b910e4c..6795a6b 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/Jira61TestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/Jira61TestCase.java
@@ -403,7 +403,7 @@
*/
public void testIssue_BEANUTILS_61_PropertyUtils_copyProperties_to_WrapDynaBean() {
String value = "copied simpleReadOnly";
- Map source = new HashMap();
+ Map<String, Object> source = new HashMap<String, Object>();
source.put("simpleReadOnly", value);
try {
PropertyUtils.copyProperties(wrapDynaBean, source);
@@ -437,7 +437,7 @@
*/
public void testIssue_BEANUTILS_61_BeanUtils_copyProperties_to_WrapDynaBean() {
String value = "copied simpleReadOnly";
- Map source = new HashMap();
+ Map<String, Object> source = new HashMap<String, Object>();
source.put("simpleReadOnly", value);
try {
BeanUtils.copyProperties(wrapDynaBean, source);
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/other/Jira18BeanFactory.java b/src/test/java/org/apache/commons/beanutils/bugs/other/Jira18BeanFactory.java
index 6755ab9..d767d23 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/other/Jira18BeanFactory.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/other/Jira18BeanFactory.java
@@ -22,7 +22,7 @@
import org.apache.commons.beanutils.bugs.Jira18TestCase;
/**
- * Factory whcih creates <i>package</i> scope beans with
+ * Factory which creates <i>package</i> scope beans with
* public methods for {@link Jira18TestCase}.
*
* @version $Id$
@@ -43,7 +43,7 @@
private final String[] indexed = new String[] {"one", "two", "three"};
private String simple = "FOO";
- private final Map mapped = new HashMap();
+ private final Map<String, Object> mapped = new HashMap<String, Object>();
/** Default Constructor */
public PackageFriendlyBean() {
diff --git a/src/test/java/org/apache/commons/beanutils/bugs/other/Jira61BeanFactory.java b/src/test/java/org/apache/commons/beanutils/bugs/other/Jira61BeanFactory.java
index 183fa8d..6ac9834 100644
--- a/src/test/java/org/apache/commons/beanutils/bugs/other/Jira61BeanFactory.java
+++ b/src/test/java/org/apache/commons/beanutils/bugs/other/Jira61BeanFactory.java
@@ -44,7 +44,7 @@
private final String[] indexed = new String[] {"one", "two", "three"};
private String simple = "FOO";
- private final Map mapped = new HashMap();
+ private final Map<String, Object> mapped = new HashMap<String, Object>();
/** Default Constructor */
public TestBean() {
diff --git a/src/test/java/org/apache/commons/beanutils/converters/ArrayConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/ArrayConverterTestCase.java
index 6f9ff03..fbec675 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/ArrayConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/ArrayConverterTestCase.java
@@ -81,8 +81,8 @@
long[] longArray = new long[] {intArray[0], intArray[1], intArray[2], intArray[3]};
Long[] LONGArray = new Long[] {new Long(intArray[0]), new Long(intArray[1]), new Long(intArray[2]), new Long(intArray[3])};
Integer[] IntegerArray = new Integer[] {new Integer(intArray[0]), new Integer(intArray[1]), new Integer(intArray[2]), new Integer(intArray[3])};
- ArrayList strList = new ArrayList();
- ArrayList longList = new ArrayList();
+ ArrayList<String> strList = new ArrayList<String>();
+ ArrayList<Long> longList = new ArrayList<Long>();
for (int i = 0; i < strArray.length; i++) {
strList.add(strArray[i]);
longList.add(LONGArray[i]);
@@ -216,7 +216,7 @@
// Test Data
String[] array = new String[] {"10", " 11", "12 ", " 13 "};
- ArrayList list = new ArrayList();
+ ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
@@ -368,7 +368,7 @@
ArrayConverter converter = new ArrayConverter(String[].class, new StringConverter());
// test underscore not allowed (the default)
- String[] result = (String[])converter.convert(String[].class, value);
+ String[] result = converter.convert(String[].class, value);
assertNotNull("result.null", result);
assertEquals("result.length", 4, result.length);
assertEquals("result[0]", "first", result[0]);
@@ -380,7 +380,7 @@
converter.setAllowedChars(new char[] {'.', '-', '_'});
// test underscore allowed
- result = (String[])converter.convert(String[].class, value);
+ result = converter.convert(String[].class, value);
assertNotNull("result.null", result);
assertEquals("result.length", 2, result.length);
assertEquals("result[0]", "first_value", result[0]);
diff --git a/src/test/java/org/apache/commons/beanutils/converters/BigDecimalConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/BigDecimalConverterTestCase.java
index be27cd7..8bb4b87 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/BigDecimalConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/BigDecimalConverterTestCase.java
@@ -73,7 +73,7 @@
}
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return BigDecimal.class;
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/BigIntegerConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/BigIntegerConverterTestCase.java
index 1bd0bb4..b550a60 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/BigIntegerConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/BigIntegerConverterTestCase.java
@@ -72,7 +72,7 @@
}
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return BigInteger.class;
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/BooleanConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/BooleanConverterTestCase.java
index 8f31707..2a0106a 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/BooleanConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/BooleanConverterTestCase.java
@@ -17,10 +17,10 @@
package org.apache.commons.beanutils.converters;
-import org.apache.commons.beanutils.ConversionException;
-
import junit.framework.TestCase;
+import org.apache.commons.beanutils.ConversionException;
+
/**
* @version $Id$
*/
@@ -95,6 +95,26 @@
}
}
+ /**
+ * Tests a conversion to another target type. This should not be possible.
+ */
+ public void testConversionToOtherType() {
+ BooleanConverter converter = new BooleanConverter();
+ try {
+ converter.convert(Integer.class, STANDARD_TRUES[0]);
+ fail("Could convert to unsupported type!");
+ } catch (ConversionException cex) {
+ // Expected result
+ }
+ }
+
+ /**
+ * Tests whether a conversion to a primitive boolean is possible.
+ */
+ public void testPrimitiveTargetClass() {
+ BooleanConverter converter = new BooleanConverter();
+ assertTrue("Wrong result", converter.convert(Boolean.TYPE, STANDARD_TRUES[0]));
+ }
protected void testConversionValues(BooleanConverter converter,
String[] trueValues, String[] falseValues) {
diff --git a/src/test/java/org/apache/commons/beanutils/converters/ByteConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/ByteConverterTestCase.java
index c7a3c1e..1448758 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/ByteConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/ByteConverterTestCase.java
@@ -70,7 +70,7 @@
return new ByteConverter(defaultValue);
}
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Byte.class;
}
@@ -137,7 +137,7 @@
*/
public void testInvalidAmount() {
Converter converter = makeConverter();
- Class clazz = Byte.class;
+ Class<?> clazz = Byte.class;
Long min = new Long(Byte.MIN_VALUE);
Long max = new Long(Byte.MAX_VALUE);
diff --git a/src/test/java/org/apache/commons/beanutils/converters/CalendarConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/CalendarConverterTestCase.java
index deab042..8fd73cb 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/CalendarConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/CalendarConverterTestCase.java
@@ -17,6 +17,7 @@
package org.apache.commons.beanutils.converters;
import java.util.Calendar;
+
import junit.framework.TestSuite;
/**
@@ -69,7 +70,7 @@
* @return The expected type
*/
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Calendar.class;
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/CharacterConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/CharacterConverterTestCase.java
index 83f9aa4..a98f6e3 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/CharacterConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/CharacterConverterTestCase.java
@@ -19,6 +19,7 @@
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
/**
@@ -80,6 +81,22 @@
assertEquals("Character Test", new Character('N'), converter.convert(Character.class, new Character('N')));
assertEquals("String Test", new Character('F'), converter.convert(Character.class, "FOO"));
assertEquals("Integer Test", new Character('3'), converter.convert(Character.class, new Integer(321)));
+ }
+
+ /**
+ * Tests whether the primitive char class can be passed as target type.
+ */
+ public void testConvertToChar() {
+ Converter converter = new CharacterConverter();
+ assertEquals("Wrong result", new Character('F'), converter.convert(Character.TYPE, "FOO"));
+ }
+
+ /**
+ * Tests a conversion to character for null input if no default value is
+ * provided.
+ */
+ public void testConvertToCharacterNullNoDefault() {
+ Converter converter = new CharacterConverter();
try {
converter.convert(Character.class, null);
fail("Expected a ConversionException for null value");
@@ -95,4 +112,17 @@
Converter converter = new CharacterConverter("C");
assertEquals("Default Test", new Character('C'), converter.convert(Character.class, null));
}
+
+ /**
+ * Tries a conversion to an unsupported type.
+ */
+ public void testConvertToUnsupportedType() {
+ Converter converter = new CharacterConverter();
+ try {
+ converter.convert(Integer.class, "Test");
+ fail("Could convert to unsupported type!");
+ } catch (ConversionException cex) {
+ // expected result
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/ClassConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/ClassConverterTestCase.java
index 0d3f451..8136a43 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/ClassConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/ClassConverterTestCase.java
@@ -150,4 +150,16 @@
}
}
+ /**
+ * Tries a conversion to an unsupported target type.
+ */
+ public void testUnsupportedTargetType() {
+ Converter converter = new ClassConverter();
+ try {
+ converter.convert(Integer.class, getClass().getName());
+ fail("Invalid target class not detected!");
+ } catch (ConversionException cex) {
+ // expected result
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/ClassReloader.java b/src/test/java/org/apache/commons/beanutils/converters/ClassReloader.java
index f872fa3..e6023e0 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/ClassReloader.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/ClassReloader.java
@@ -17,10 +17,10 @@
package org.apache.commons.beanutils.converters;
-import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.io.InputStream;
/**
* A special classloader useful for testing j2ee-like scenarios.
@@ -55,7 +55,7 @@
* Given a class already in the classpath of a parent classloader,
* reload that class via this classloader.
*/
- public Class reload(Class clazz) throws FileNotFoundException, IOException {
+ public Class<?> reload(Class<?> clazz) throws FileNotFoundException, IOException {
String className = clazz.getName();
String classFile = className.replace('.', '/') + ".class";
InputStream classStream = getParent().getResourceAsStream(classFile);
@@ -77,7 +77,7 @@
byte[] classData = baos.toByteArray();
// now we have the raw class data, let's turn it into a class
- Class newClass = defineClass(className, classData, 0, classData.length);
+ Class<?> newClass = defineClass(className, classData, 0, classData.length);
resolveClass(newClass);
return newClass;
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/ClassReloaderTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/ClassReloaderTestCase.java
index 78db5d8..66e23f8 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/ClassReloaderTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/ClassReloaderTestCase.java
@@ -51,8 +51,8 @@
ClassLoader sharedLoader = this.getClass().getClassLoader();
ClassReloader componentLoader = new ClassReloader(sharedLoader);
- Class sharedClass = DummyClass.class;
- Class componentClass = componentLoader.reload(sharedClass);
+ Class<?> sharedClass = DummyClass.class;
+ Class<?> componentClass = componentLoader.reload(sharedClass);
// the two Class objects contain the same bytecode, but are not equal
assertTrue(sharedClass != componentClass);
diff --git a/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestBase.java b/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestBase.java
index 49d43a6..2d26749 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestBase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestBase.java
@@ -25,8 +25,9 @@
import java.util.Locale;
import junit.framework.TestCase;
-import org.apache.commons.beanutils.Converter;
+
import org.apache.commons.beanutils.ConversionException;
+import org.apache.commons.beanutils.Converter;
/**
* Abstract base for <Date>Converter classes.
@@ -39,7 +40,7 @@
// ------------------------------------------------------------------------
/**
- * Construtc a new test case.
+ * Construct a new test case.
* @param name Name of the test
*/
public DateConverterTestBase(String name) {
@@ -65,7 +66,7 @@
* Return the expected type
* @return The expected type
*/
- protected abstract Class getExpectedType();
+ protected abstract Class<?> getExpectedType();
/**
* Convert from a Calendar to the appropriate Date type
@@ -152,7 +153,7 @@
/**
* Test default String to type conversion
*
- * N.B. This method is overriden by test case
+ * N.B. This method is overridden by test case
* implementations for java.sql.Date/Time/Timestamp
*/
public void testDefaultStringToTypeConvert() {
@@ -394,8 +395,8 @@
String msg = "Converting '" + valueType + "' value '" + value + "'";
try {
Object result = converter.convert(getExpectedType(), value);
- Class resultType = (result == null ? null : result.getClass());
- Class expectType = (expected == null ? null : expected.getClass());
+ Class<?> resultType = (result == null ? null : result.getClass());
+ Class<?> expectType = (expected == null ? null : expected.getClass());
assertEquals("TYPE " + msg, expectType, resultType);
assertEquals("VALUE " + msg, expected, result);
} catch (Exception ex) {
@@ -414,8 +415,8 @@
String msg = "Converting '" + valueType + "' value '" + value + "' to String";
try {
Object result = converter.convert(String.class, value);
- Class resultType = (result == null ? null : result.getClass());
- Class expectType = (expected == null ? null : expected.getClass());
+ Class<?> resultType = (result == null ? null : result.getClass());
+ Class<?> expectType = (expected == null ? null : expected.getClass());
assertEquals("TYPE " + msg, expectType, resultType);
assertEquals("VALUE " + msg, expected, result);
} catch (Exception ex) {
diff --git a/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestCase.java
index 58c1173..57f8568 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestCase.java
@@ -82,7 +82,7 @@
* @return The expected type
*/
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Date.class;
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/DoubleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/DoubleConverterTestCase.java
index d5e0710..1deb4f5 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/DoubleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/DoubleConverterTestCase.java
@@ -71,7 +71,7 @@
}
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Double.class;
}
@@ -130,12 +130,12 @@
assertEquals(
message[i] + " to Double",
expected[i].doubleValue(),
- ((Double)(converter.convert(Double.class,input[i]))).doubleValue(),
+ (converter.convert(Double.class,input[i])).doubleValue(),
0.00001D);
assertEquals(
message[i] + " to double",
expected[i].doubleValue(),
- ((Double)(converter.convert(Double.TYPE,input[i]))).doubleValue(),
+ (converter.convert(Double.TYPE,input[i])).doubleValue(),
0.00001D);
assertEquals(
message[i] + " to null type",
diff --git a/src/test/java/org/apache/commons/beanutils/converters/FileConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/FileConverterTestCase.java
index 4384640..b2917ba 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/FileConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/FileConverterTestCase.java
@@ -22,6 +22,7 @@
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
@@ -63,7 +64,7 @@
return new FileConverter();
}
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return File.class;
}
@@ -94,5 +95,16 @@
}
}
+ /**
+ * Tries a conversion to an unsupported target type.
+ */
+ public void testUnsupportedTargetType() {
+ try {
+ converter.convert(Integer.class, "/tmp");
+ fail("Could convert to unsupported type!");
+ } catch (ConversionException cex) {
+ // expected result
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/FloatConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/FloatConverterTestCase.java
index ade1ff7..8d58f2b 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/FloatConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/FloatConverterTestCase.java
@@ -71,7 +71,7 @@
}
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Float.class;
}
@@ -130,12 +130,12 @@
assertEquals(
message[i] + " to Float",
expected[i].floatValue(),
- ((Float)(converter.convert(Float.class,input[i]))).floatValue(),
+ (converter.convert(Float.class,input[i])).floatValue(),
0.00001);
assertEquals(
message[i] + " to float",
expected[i].floatValue(),
- ((Float)(converter.convert(Float.TYPE,input[i]))).floatValue(),
+ (converter.convert(Float.TYPE,input[i])).floatValue(),
0.00001);
assertEquals(
message[i] + " to null type",
@@ -151,7 +151,7 @@
*/
public void testInvalidAmount() {
Converter converter = makeConverter();
- Class clazz = Float.class;
+ Class<?> clazz = Float.class;
Double max = new Double(Float.MAX_VALUE);
Double tooBig = new Double(Double.MAX_VALUE);
diff --git a/src/test/java/org/apache/commons/beanutils/converters/IntegerConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/IntegerConverterTestCase.java
index b9f1391..b8fabf3 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/IntegerConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/IntegerConverterTestCase.java
@@ -19,6 +19,7 @@
import junit.framework.TestSuite;
+import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
@@ -71,7 +72,7 @@
}
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Integer.class;
}
@@ -138,7 +139,7 @@
*/
public void testInvalidAmount() {
Converter converter = makeConverter();
- Class clazz = Integer.class;
+ Class<?> clazz = Integer.class;
Long min = new Long(Integer.MIN_VALUE);
Long max = new Long(Integer.MAX_VALUE);
@@ -167,5 +168,18 @@
// expected result
}
}
+
+ /**
+ * Tests whether an invalid default object causes an exception.
+ */
+ public void testInvalidDefaultObject() {
+ NumberConverter converter = makeConverter();
+ try {
+ converter.setDefaultValue("notANumber");
+ fail("Invalid default value not detected!");
+ } catch (ConversionException cex) {
+ // expected result
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/LongConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/LongConverterTestCase.java
index 87c2f32..269b68e 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/LongConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/LongConverterTestCase.java
@@ -71,7 +71,7 @@
}
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Long.class;
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/MemoryTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/MemoryTestCase.java
index 74618a3..45dc58f 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/MemoryTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/MemoryTestCase.java
@@ -19,10 +19,11 @@
import java.lang.ref.WeakReference;
-import org.apache.commons.beanutils.Converter;
-import org.apache.commons.beanutils.ConvertUtils;
import junit.framework.TestCase;
+import org.apache.commons.beanutils.ConvertUtils;
+import org.apache.commons.beanutils.Converter;
+
/**
* This class provides a number of unit tests related to classloaders and
* garbage collection, particularly in j2ee-like situations.
@@ -39,7 +40,7 @@
Thread.currentThread().setContextClassLoader(componentLoader);
Thread.currentThread().setContextClassLoader(origContextClassLoader);
- WeakReference ref = new WeakReference(componentLoader);
+ WeakReference<ClassLoader> ref = new WeakReference<ClassLoader>(componentLoader);
componentLoader = null;
forceGarbageCollection(ref);
@@ -124,7 +125,7 @@
// Emulate a container "undeploying" component #1. This should
// make component loader available for garbage collection (we hope)
- WeakReference weakRefToComponent1 = new WeakReference(componentLoader1);
+ WeakReference<ClassLoader> weakRefToComponent1 = new WeakReference<ClassLoader>(componentLoader1);
componentLoader1 = null;
// force garbage collection and verify that the componentLoader
@@ -179,7 +180,7 @@
// Here we pretend we're running inside the component, and that
// a class FloatConverter has been loaded from the component's
// private classpath.
- Class newFloatConverterClass = componentLoader.reload(FloatConverter.class);
+ Class<?> newFloatConverterClass = componentLoader.reload(FloatConverter.class);
Object newFloatConverter = newFloatConverterClass.newInstance();
assertTrue(newFloatConverter.getClass().getClassLoader() == componentLoader);
@@ -218,7 +219,7 @@
Thread.currentThread().setContextClassLoader(origContextClassLoader);
// Emulate a container "undeploying" the component. This should
// make component loader available for garbage collection (we hope)
- WeakReference weakRefToComponent = new WeakReference(componentLoader);
+ WeakReference<ClassLoader> weakRefToComponent = new WeakReference<ClassLoader>(componentLoader);
componentLoader = null;
// force garbage collection and verify that the componentLoader
@@ -254,7 +255,7 @@
* else we were not able to trigger garbage collection; there is no way
* to tell these scenarios apart.</p>
*/
- private void forceGarbageCollection(WeakReference target) {
+ private void forceGarbageCollection(WeakReference<?> target) {
int bytes = 2;
while(target.get() != null) {
@@ -266,7 +267,8 @@
// all data (including the target) rather than simply collecting
// this easily-reclaimable memory!
try {
- byte[] b = new byte[bytes];
+ @SuppressWarnings("unused")
+ byte[] b = new byte[bytes];
bytes = bytes * 2;
} catch(OutOfMemoryError e) {
// well that sure should have forced a garbage collection
diff --git a/src/test/java/org/apache/commons/beanutils/converters/NumberConverterTestBase.java b/src/test/java/org/apache/commons/beanutils/converters/NumberConverterTestBase.java
index 1baf848..b048def 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/NumberConverterTestBase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/NumberConverterTestBase.java
@@ -49,7 +49,7 @@
protected abstract NumberConverter makeConverter();
protected abstract NumberConverter makeConverter(Object defaultValue);
- protected abstract Class getExpectedType();
+ protected abstract Class<?> getExpectedType();
// ------------------------------------------------------------------------
@@ -289,6 +289,17 @@
}
/**
+ * Convert String --> Number if the target type is not defined. Then the
+ * default type should be used.
+ */
+ public void testStringToNumberDefaultType() {
+ NumberConverter converter = makeConverter();
+ converter.setUseLocaleFormat(false);
+
+ assertEquals("Default Convert " + numbers[0], numbers[0], converter.convert(null, numbers[0].toString()));
+ }
+
+ /**
* Convert Boolean --> Number (default conversion)
*/
public void testBooleanToNumberDefault() {
@@ -407,5 +418,21 @@
// expected result
}
}
+
+ /**
+ * Tests a conversion to an unsupported type if a default value is set.
+ */
+ public void testInvalidTypeWithDefault() {
+
+ NumberConverter converter = makeConverter(42);
+
+ try {
+ converter.convert(Object.class, numbers[0]);
+ fail("Invalid type with default test, expected ConversionException");
+ } catch(ConversionException e) {
+ // expected result
+ }
+ }
+
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/ShortConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/ShortConverterTestCase.java
index 9ed164c..3b41caa 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/ShortConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/ShortConverterTestCase.java
@@ -71,7 +71,7 @@
}
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Short.class;
}
@@ -138,7 +138,7 @@
*/
public void testInvalidAmount() {
Converter converter = makeConverter();
- Class clazz = Short.class;
+ Class<?> clazz = Short.class;
Long min = new Long(Short.MIN_VALUE);
Long max = new Long(Short.MAX_VALUE);
diff --git a/src/test/java/org/apache/commons/beanutils/converters/SqlDateConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/SqlDateConverterTestCase.java
index 8795b21..644e81f 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/SqlDateConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/SqlDateConverterTestCase.java
@@ -111,7 +111,7 @@
* @return The expected type
*/
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Date.class;
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/SqlTimeConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/SqlTimeConverterTestCase.java
index 2f8cb0f..c67e63d 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/SqlTimeConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/SqlTimeConverterTestCase.java
@@ -134,7 +134,7 @@
* @return The expected type
*/
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Time.class;
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/SqlTimestampConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/SqlTimestampConverterTestCase.java
index 1c81f19..d964d52 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/SqlTimestampConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/SqlTimestampConverterTestCase.java
@@ -131,7 +131,7 @@
* @return The expected type
*/
@Override
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return Timestamp.class;
}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/StringConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/StringConverterTestCase.java
new file mode 100644
index 0000000..8054f9a
--- /dev/null
+++ b/src/test/java/org/apache/commons/beanutils/converters/StringConverterTestCase.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.beanutils.converters;
+
+import junit.framework.TestCase;
+
+import org.apache.commons.beanutils.ConversionException;
+
+/**
+ * Test case for {@code StringConverter}.
+ *
+ * @version $Id: $
+ */
+public class StringConverterTestCase extends TestCase {
+ /** The converter to be tested. */
+ private StringConverter converter;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ converter = new StringConverter();
+ }
+
+ /**
+ * Tests whether the correct default type is returned.
+ */
+ public void testDefaultType() {
+ assertEquals("Wrong default type", String.class, converter.getDefaultType());
+ }
+
+ /**
+ * Tests a conversion to a string type.
+ */
+ public void testConvertToTypeString() {
+ Object value = new Object();
+ String strVal = converter.convert(String.class, value);
+ assertEquals("Wrong conversion result", value.toString(), strVal);
+ }
+
+ /**
+ * Tries to convert an object to an unsupported type.
+ */
+ public void testConvertToUnsupportedType() {
+ try {
+ converter.convert(Integer.class, new Object());
+ fail("No conversion exception thrown!");
+ } catch(ConversionException cex) {
+ // expected result
+ }
+ }
+}
diff --git a/src/test/java/org/apache/commons/beanutils/converters/URLConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/converters/URLConverterTestCase.java
index c667b9c..e871f8f 100644
--- a/src/test/java/org/apache/commons/beanutils/converters/URLConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/converters/URLConverterTestCase.java
@@ -17,13 +17,14 @@
package org.apache.commons.beanutils.converters;
-import junit.framework.TestSuite;
-import junit.framework.TestCase;
-
-import org.apache.commons.beanutils.Converter;
-
import java.net.URL;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import org.apache.commons.beanutils.ConversionException;
+import org.apache.commons.beanutils.Converter;
+
/**
* Test Case for the URLConverter class.
@@ -63,7 +64,7 @@
return new URLConverter();
}
- protected Class getExpectedType() {
+ protected Class<?> getExpectedType() {
return URL.class;
}
@@ -113,5 +114,16 @@
}
}
+ /**
+ * Tests a conversion to an unsupported type.
+ */
+ public void testUnsupportedType() {
+ try {
+ converter.convert(Integer.class, "http://www.apache.org");
+ fail("Unsupported type could be converted!");
+ } catch (ConversionException cex) {
+ // expected result
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/beanutils/locale/LocaleBeanificationTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/LocaleBeanificationTestCase.java
index 5ec3a87..b1976ef 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/LocaleBeanificationTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/LocaleBeanificationTestCase.java
@@ -17,24 +17,23 @@
package org.apache.commons.beanutils.locale;
-import java.lang.ref.WeakReference;
import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.Map;
import java.util.WeakHashMap;
-import junit.framework.TestCase;
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
-import org.apache.commons.logging.LogFactory;
-
import org.apache.commons.beanutils.BeanUtilsTestCase;
import org.apache.commons.beanutils.ContextClassLoaderLocal;
-import org.apache.commons.beanutils.PrimitiveBean;
-import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.ConversionException;
+import org.apache.commons.beanutils.ConvertUtils;
+import org.apache.commons.beanutils.PrimitiveBean;
import org.apache.commons.beanutils.locale.converters.LongLocaleConverter;
+import org.apache.commons.logging.LogFactory;
/**
* <p>
@@ -144,11 +143,11 @@
// many thanks to Juozas Baliuka for suggesting this methodology
TestClassLoader loader = new TestClassLoader();
- ReferenceQueue<?> queue = new ReferenceQueue<Object>();
- WeakReference loaderReference = new WeakReference(loader, queue);
+ ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
+ WeakReference<ClassLoader> loaderReference = new WeakReference<ClassLoader>(loader, queue);
Integer test = new Integer(1);
- WeakReference testReference = new WeakReference(test, queue);
+ WeakReference<Integer> testReference = new WeakReference<Integer>(test, queue);
//Map map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.HARD, true);
Map<TestClassLoader, Integer> map = new WeakHashMap<TestClassLoader, Integer>();
map.put(loader, test);
@@ -224,8 +223,8 @@
thread.start();
thread.join();
- WeakReference beanUtilsReference = new WeakReference(thread.beanUtils);
- WeakReference convertUtilsReference = new WeakReference(thread.convertUtils);
+ WeakReference<LocaleBeanUtilsBean> beanUtilsReference = new WeakReference<LocaleBeanUtilsBean>(thread.beanUtils);
+ WeakReference<LocaleConvertUtilsBean> convertUtilsReference = new WeakReference<LocaleConvertUtilsBean>(thread.convertUtils);
assertNotNull("Weak reference released early (1)", loaderReference.get());
assertNotNull("Weak reference released early (2)", beanUtilsReference.get());
@@ -314,9 +313,9 @@
class CCLLTesterThread extends Thread {
private final Signal signal;
- private final ContextClassLoaderLocal ccll;
+ private final ContextClassLoaderLocal<Integer> ccll;
- CCLLTesterThread(Signal signal, ContextClassLoaderLocal ccll) {
+ CCLLTesterThread(Signal signal, ContextClassLoaderLocal<Integer> ccll) {
this.signal = signal;
this.ccll = ccll;
}
@@ -334,8 +333,8 @@
}
}
- ContextClassLoaderLocal ccll = new ContextClassLoaderLocal();
- ccll.set(new Integer(1776));
+ ContextClassLoaderLocal<Integer> ccll = new ContextClassLoaderLocal<Integer>();
+ ccll.set(1776);
assertEquals("Start thread sets value", new Integer(1776), ccll.get());
Signal signal = new Signal();
@@ -369,11 +368,11 @@
try {
signal.setSignal(3);
LocaleConvertUtils.register(new LocaleConverter() {
- public Object convert(Class type, Object value) {
- return new Integer(9);
+ public <T> T convert(Class<T> type, Object value) {
+ return ConvertUtils.primitiveToWrapper(type).cast(9);
}
- public Object convert(Class type, Object value, String pattern) {
- return new Integer(9);
+ public <T> T convert(Class<T> type, Object value, String pattern) {
+ return ConvertUtils.primitiveToWrapper(type).cast(9);
}
}, Integer.TYPE, Locale.getDefault());
LocaleBeanUtils.setProperty(bean, "int", "1");
@@ -394,11 +393,11 @@
assertEquals("Wrong property value (1)", 1, bean.getInt());
LocaleConvertUtils.register(new LocaleConverter() {
- public Object convert(Class type, Object value) {
- return new Integer(5);
+ public <T> T convert(Class<T> type, Object value) {
+ return ConvertUtils.primitiveToWrapper(type).cast(5);
}
- public Object convert(Class type, Object value, String pattern) {
- return new Integer(5);
+ public <T> T convert(Class<T> type, Object value, String pattern) {
+ return ConvertUtils.primitiveToWrapper(type).cast(5);
}
}, Integer.TYPE, Locale.getDefault());
LocaleBeanUtils.setProperty(bean, "int", "1");
@@ -467,7 +466,7 @@
/** Tests whether the unset method works*/
public void testContextClassLoaderUnset() throws Exception {
LocaleBeanUtilsBean beanOne = new LocaleBeanUtilsBean();
- ContextClassLoaderLocal ccll = new ContextClassLoaderLocal();
+ ContextClassLoaderLocal<LocaleBeanUtilsBean> ccll = new ContextClassLoaderLocal<LocaleBeanUtilsBean>();
ccll.set(beanOne);
assertEquals("Start thread gets right instance", beanOne, ccll.get());
ccll.unset();
diff --git a/src/test/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsTestCase.java
index fa4d04f..27e6096 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsTestCase.java
@@ -25,9 +25,10 @@
import java.text.NumberFormat;
import java.util.Locale;
-import junit.framework.TestCase;
import junit.framework.Test;
+import junit.framework.TestCase;
import junit.framework.TestSuite;
+
import org.apache.commons.beanutils.ConversionException;
@@ -134,8 +135,6 @@
*/
public void testNegativeScalar() {
- Object value = null;
-
/* fixme Boolean converters not implemented at this point
value = LocaleConvertUtils.convert("foo", Boolean.TYPE);
...
@@ -146,14 +145,14 @@
try {
- value = LocaleConvertUtils.convert("foo", Byte.TYPE);
+ LocaleConvertUtils.convert("foo", Byte.TYPE);
fail("Should have thrown conversion exception (1)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Byte.class);
+ LocaleConvertUtils.convert("foo", Byte.class);
fail("Should have thrown conversion exception (2)");
} catch (ConversionException e) {
// Expected result
@@ -169,70 +168,70 @@
*/
try {
- value = LocaleConvertUtils.convert("foo", Double.TYPE);
+ LocaleConvertUtils.convert("foo", Double.TYPE);
fail("Should have thrown conversion exception (3)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Double.class);
+ LocaleConvertUtils.convert("foo", Double.class);
fail("Should have thrown conversion exception (4)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Float.TYPE);
+ LocaleConvertUtils.convert("foo", Float.TYPE);
fail("Should have thrown conversion exception (5)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Float.class);
+ LocaleConvertUtils.convert("foo", Float.class);
fail("Should have thrown conversion exception (6)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Integer.TYPE);
+ LocaleConvertUtils.convert("foo", Integer.TYPE);
fail("Should have thrown conversion exception (7)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Integer.class);
+ LocaleConvertUtils.convert("foo", Integer.class);
fail("Should have thrown conversion exception (8)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Byte.TYPE);
+ LocaleConvertUtils.convert("foo", Byte.TYPE);
fail("Should have thrown conversion exception (9)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Long.class);
+ LocaleConvertUtils.convert("foo", Long.class);
fail("Should have thrown conversion exception (10)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Short.TYPE);
+ LocaleConvertUtils.convert("foo", Short.TYPE);
fail("Should have thrown conversion exception (11)");
} catch (ConversionException e) {
// Expected result
}
try {
- value = LocaleConvertUtils.convert("foo", Short.class);
+ LocaleConvertUtils.convert("foo", Short.class);
fail("Should have thrown conversion exception (12)");
} catch (ConversionException e) {
// Expected result
@@ -629,6 +628,17 @@
assertEquals("Integer Array Value", new Integer(123), ((Integer[])result)[0]);
}
+ /**
+ * Tests a conversion if there is no suitable converter registered. In this
+ * case, the string converter is used, and the passed in target type is
+ * ignored. (This test is added to prevent a regression after the locale
+ * converters have been generified.)
+ */
+ public void testDefaultToStringConversionUnsupportedType() {
+ Integer value = 20131101;
+ assertEquals("Wrong result", value.toString(),
+ LocaleConvertUtils.convert(value.toString(), getClass()));
+ }
// -------------------------------------------------------- Private Methods
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/BaseLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/BaseLocaleConverterTestCase.java
index 702b007..f627f55 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/BaseLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/BaseLocaleConverterTestCase.java
@@ -17,8 +17,10 @@
package org.apache.commons.beanutils.locale.converters;
-import junit.framework.TestCase;
import java.util.Locale;
+
+import junit.framework.TestCase;
+
import org.apache.commons.beanutils.locale.BaseLocaleConverter;
/**
@@ -180,16 +182,16 @@
}
/**
- * Test Converting Value To a spcified Type
+ * Test Converting Value To a specified Type
*/
- protected void convertValueToType(BaseLocaleConverter converter, Class clazz, Object value, String pattern, Object expectedValue) {
+ protected void convertValueToType(BaseLocaleConverter converter, Class<?> clazz, Object value, String pattern, Object expectedValue) {
convertValueToType(converter, "", clazz, value, pattern, expectedValue);
}
/**
- * Test Converting Value To a spcified Type
+ * Test Converting Value To a specified Type
*/
- protected void convertValueToType(BaseLocaleConverter converter, String msgId, Class clazz, Object value, String pattern, Object expectedValue) {
+ protected void convertValueToType(BaseLocaleConverter converter, String msgId, Class<?> clazz, Object value, String pattern, Object expectedValue) {
// Convert value with no pattern
try {
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/BigDecimalLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/BigDecimalLocaleConverterTestCase.java
index 43fd35b..9d33826 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/BigDecimalLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/BigDecimalLocaleConverterTestCase.java
@@ -103,9 +103,9 @@
//
// BaseLocaleConverter completely ignores the type - so even if we specify
// Double.class here it still returns a BigDecimal.
- // **** SHOULD IMPLEMENT THIS BEHAVIOUR ****
+ // **** This has been changed due to BEANUTILS-449 ****
// **************************************************************************
- convertValueToType(converter, "(B)", Double.class, localizedDecimalValue, localizedDecimalPattern, expectedValue);
+ //convertValueToType(converter, "(B)", Double.class, localizedDecimalValue, localizedDecimalPattern, expectedValue);
// ------------- Construct with non-localized pattern ------------
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/BigIntegerLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/BigIntegerLocaleConverterTestCase.java
index b8d27e5..e2354d8 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/BigIntegerLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/BigIntegerLocaleConverterTestCase.java
@@ -19,6 +19,8 @@
import java.math.BigInteger;
+import org.apache.commons.beanutils.ConversionException;
+
/**
* Test Case for the BigIntegerLocaleConverter class.
*
@@ -102,9 +104,9 @@
//
// BaseLocaleConverter completely ignores the type - so even if we specify
// Double.class here it still returns a BigInteger.
- // **** SHOULD IMPLEMENT THIS BEHAVIOUR ****
+ // **** This has been changed due to BEANUTILS-449 ****
// **************************************************************************
- convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
+ //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
// ------------- Construct with non-localized pattern ------------
@@ -259,7 +261,19 @@
}
-
+ /**
+ * Tries to convert to an unsupported type. This tests behavior of the base
+ * class. All locale converters should react in the same way.
+ */
+ public void testUnsupportedType() {
+ converter = new BigIntegerLocaleConverter();
+ try {
+ converter.convert(getClass(), "test", null);
+ fail("Unsupported type not detected!");
+ } catch (ConversionException cex) {
+ // expected result
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/ByteLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/ByteLocaleConverterTestCase.java
index 6546714..da5cf7b 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/ByteLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/ByteLocaleConverterTestCase.java
@@ -108,9 +108,9 @@
//
// BaseLocaleConverter completely ignores the type - so even if we specify
// Double.class here it still returns a Byte.
- // **** SHOULD IMPLEMENT THIS BEHAVIOUR ****
+ // **** This has been changed due to BEANUTILS-449 ****
// **************************************************************************
- convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
+ //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
// ------------- Construct with non-localized pattern ------------
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/DateLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/DateLocaleConverterTestCase.java
index 76be586..b0163dc 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/DateLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/DateLocaleConverterTestCase.java
@@ -17,15 +17,14 @@
package org.apache.commons.beanutils.locale.converters;
-import java.text.SimpleDateFormat;
-import java.text.ParseException;
import java.text.DateFormatSymbols;
-
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
import java.util.Locale;
import org.apache.commons.beanutils.ConversionException;
-import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
/**
* Test Case for the DateLocaleConverter class.
@@ -239,9 +238,9 @@
//
// BaseLocaleConverter completely ignores the type - so even if we specify
// Double.class here it still returns a Date.
- // **** SHOULD IMPLEMENT THIS BEHAVIOUR ****
+ // **** This has been changed due to BEANUTILS-449 ****
// **************************************************************************
- convertValueToType(converter, "(B)", String.class, localizedDateValue, localizedDatePattern, expectedValue);
+ //convertValueToType(converter, "(B)", String.class, localizedDateValue, localizedDatePattern, expectedValue);
// ------------- Construct with non-localized pattern ------------
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/DoubleLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/DoubleLocaleConverterTestCase.java
index 630955d..4e84da5 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/DoubleLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/DoubleLocaleConverterTestCase.java
@@ -102,9 +102,9 @@
//
// BaseLocaleConverter completely ignores the type - so even if we specify
// Double.class here it still returns a Double.
- // **** SHOULD IMPLEMENT THIS BEHAVIOUR ****
+ // **** This has been changed due to BEANUTILS-449 ****
// **************************************************************************
- convertValueToType(converter, "(B)", Integer.class, localizedDecimalValue, localizedDecimalPattern, expectedValue);
+ //convertValueToType(converter, "(B)", Integer.class, localizedDecimalValue, localizedDecimalPattern, expectedValue);
// ------------- Construct with non-localized pattern ------------
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverterTestCase.java
index 3ad17ec..b87175f 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverterTestCase.java
@@ -107,9 +107,9 @@
//
// BaseLocaleConverter completely ignores the type - so even if we specify
// Float.class here it still returns a Float.
- // **** SHOULD IMPLEMENT THIS BEHAVIOUR ****
+ // **** This has been changed due to BEANUTILS-449 ****
// **************************************************************************
- convertValueToType(converter, "(B)", Integer.class, localizedDecimalValue, localizedDecimalPattern, expectedValue);
+ //convertValueToType(converter, "(B)", Integer.class, localizedDecimalValue, localizedDecimalPattern, expectedValue);
// ------------- Construct with non-localized pattern ------------
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/IntegerLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/IntegerLocaleConverterTestCase.java
index 896682f..e1ca442 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/IntegerLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/IntegerLocaleConverterTestCase.java
@@ -101,9 +101,9 @@
//
// BaseLocaleConverter completely ignores the type - so even if we specify
// Double.class here it still returns a Integer.
- // **** SHOULD IMPLEMENT THIS BEHAVIOUR ****
+ // **** This has been changed due to BEANUTILS-449 ****
// **************************************************************************
- convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
+ //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
// ------------- Construct with non-localized pattern ------------
@@ -272,6 +272,15 @@
assertEquals("Convert Long", value, converter.convert(new Long(value.intValue())));
}
-
+ /**
+ * Tests whether a conversion to a primitive type can be performed.
+ */
+ public void testToPrimitiveType() {
+ converter = new IntegerLocaleConverter();
+ Integer value = 20131028;
+ Class<Integer> target = Integer.TYPE;
+ int result = converter.convert(target, (Object) value.toString());
+ assertEquals("Wrong result", value.intValue(), result);
+ }
}
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/LongLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/LongLocaleConverterTestCase.java
index 75336a0..2f5ff40 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/LongLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/LongLocaleConverterTestCase.java
@@ -101,9 +101,9 @@
//
// BaseLocaleConverter completely ignores the type - so even if we specify
// Double.class here it still returns a Long.
- // **** SHOULD IMPLEMENT THIS BEHAVIOUR ****
+ // **** This has been changed due to BEANUTILS-449 ****
// **************************************************************************
- convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
+ //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
// ------------- Construct with non-localized pattern ------------
diff --git a/src/test/java/org/apache/commons/beanutils/locale/converters/ShortLocaleConverterTestCase.java b/src/test/java/org/apache/commons/beanutils/locale/converters/ShortLocaleConverterTestCase.java
index 4bf4f2a..59746e4 100644
--- a/src/test/java/org/apache/commons/beanutils/locale/converters/ShortLocaleConverterTestCase.java
+++ b/src/test/java/org/apache/commons/beanutils/locale/converters/ShortLocaleConverterTestCase.java
@@ -101,9 +101,9 @@
//
// BaseLocaleConverter completely ignores the type - so even if we specify
// Double.class here it still returns a Short.
- // **** SHOULD IMPLEMENT THIS BEHAVIOUR ****
+ // **** This has been changed due to BEANUTILS-449 ****
// **************************************************************************
- convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
+ //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue);
// ------------- Construct with non-localized pattern ------------