Browse Source

Correctly set auto-growing array's element

Prior to this commit, the implementation of processKeyedProperty() in
AbstractNestablePropertyAccessor resulted in a
`java.lang.IllegalArgumentException: array element type mismatch` when
the property expression had more than one property key and the last key
should cause the array to grow automatically.

For example, given a property `int[][] multiArray` and property
expression `multiArray[1][3]`, the `processKeyedProperty()` method
created a new array object and assigned it to `multiArray`; whereas,
the new array object should have be assigned to `multiArray[1]`.

This commit fixes this issue.

Closes gh-26600
pull/26612/head
nullzl 4 years ago committed by Sam Brannen
parent
commit
a33eac3ec0
  1. 6
      spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java
  2. 6
      spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java

6
spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java

@ -305,8 +305,10 @@ public abstract class AbstractNestablePropertyAccessor extends AbstractPropertyA @@ -305,8 +305,10 @@ public abstract class AbstractNestablePropertyAccessor extends AbstractPropertyA
Class<?> componentType = propValue.getClass().getComponentType();
Object newArray = Array.newInstance(componentType, arrayIndex + 1);
System.arraycopy(propValue, 0, newArray, 0, length);
setPropertyValue(tokens.actualName, newArray);
propValue = getPropertyValue(tokens.actualName);
int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
String propName = tokens.canonicalName.substring(0, lastKeyIndex);
setPropertyValue(propName, newArray);
propValue = getPropertyValue(propName);
}
Array.set(propValue, arrayIndex, convertedValue);
}

6
spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java

@ -99,6 +99,12 @@ public class BeanWrapperAutoGrowingTests { @@ -99,6 +99,12 @@ public class BeanWrapperAutoGrowingTests {
assertThat(bean.getMultiArray()[0][0]).isInstanceOf(Bean.class);
}
@Test
public void setPropertyValueAutoGrowMultiDimensionalArray() {
wrapper.setPropertyValue("multiArray[2][3]", new Bean());
assertThat(bean.getMultiArray()[2][3]).isInstanceOf(Bean.class);
}
@Test
public void getPropertyValueAutoGrowList() {
assertNotNull(wrapper.getPropertyValue("list[0]"));

Loading…
Cancel
Save