Skip to content

Commit fb2ae68

Browse files
committed
fix: convert JsonValue in varargs methods
1 parent d9bda26 commit fb2ae68

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/main/java/com/flowingcode/vaadin/jsonmigration/JsonMigrationHelper25.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import elemental.json.JsonArray;
2828
import elemental.json.JsonObject;
2929
import elemental.json.JsonValue;
30+
import java.lang.reflect.Array;
3031
import java.util.concurrent.CompletableFuture;
3132
import lombok.AllArgsConstructor;
3233
import lombok.NoArgsConstructor;
@@ -58,7 +59,18 @@ public JsonValue convertToJsonValue(Object object) {
5859
@SneakyThrows
5960
public Object invoke(Method method, Object instance, Object... args) {
6061
Object[] convertedArgs = null;
62+
63+
int j = args.length - 1;
6164
Class<?> parameterTypes[] = method.getParameterTypes();
65+
if (method.isVarArgs() && j >= 0 && args[j] instanceof Object[]) {
66+
Object[] convertedArray =
67+
convertArray((Object[]) args[j], parameterTypes[j].getComponentType());
68+
if (convertedArray != null) {
69+
convertedArgs = Arrays.copyOf(args, args.length);
70+
convertedArgs[j] = convertedArray;
71+
}
72+
}
73+
6274
for (int i = 0; i < parameterTypes.length; i++) {
6375
if (args[i] instanceof JsonValue && parameterTypes[i] == BaseJsonNode.class) {
6476

@@ -74,6 +86,33 @@ public Object invoke(Method method, Object instance, Object... args) {
7486
return method.invoke(instance, convertedArgs);
7587
}
7688

89+
90+
private static <T> T[] convertArray(Object[] array, Class<? extends T> newType) {
91+
T[] convertedArray = null;
92+
if (newType.isAssignableFrom(BaseJsonNode.class)) {
93+
for (int i = 0; i < array.length; i++) {
94+
if (array[i] instanceof JsonValue) {
95+
if (convertedArray == null) {
96+
@SuppressWarnings("unchecked")
97+
T[] copy = (newType == Object.class)
98+
? (T[]) new Object[array.length]
99+
: (T[]) Array.newInstance(newType, array.length);
100+
if (i>0) {
101+
System.arraycopy(array, 0, copy, 0, i);
102+
}
103+
convertedArray = copy;
104+
}
105+
@SuppressWarnings("unchecked")
106+
T t = (T) convertToJsonNode((JsonValue) array[i]);
107+
convertedArray[i] = t;
108+
} else if (convertedArray != null) {
109+
convertedArray[i] = newType.cast(array[i]);
110+
}
111+
}
112+
}
113+
return convertedArray;
114+
}
115+
77116
private static JsonValue convertToJsonValue(JsonNode jsonNode) {
78117
switch (jsonNode.getNodeType()) {
79118
case OBJECT:

0 commit comments

Comments
 (0)