1
1
package io .github .jsonSnapshot ;
2
2
3
+ import java .lang .reflect .Constructor ;
3
4
import java .lang .reflect .Field ;
4
5
5
6
public class SnapshotCaptor {
@@ -50,7 +51,8 @@ public Object removeIgnored(Object value) {
50
51
51
52
private Object shallowCopy (Object value ) {
52
53
try {
53
- Object newValue = this .argumentClass .newInstance ();
54
+ Object newValue = constructCopy (this .argumentClass );
55
+
54
56
Field [] fields = this .argumentClass .getDeclaredFields ();
55
57
56
58
for (Field field : fields ) {
@@ -68,4 +70,35 @@ private Object shallowCopy(Object value) {
68
70
throw new SnapshotMatchException ("Class " + this .argumentClass .getSimpleName () + " must have a default empty constructor!" );
69
71
}
70
72
}
73
+
74
+ private Object constructCopy (Class <?> argumentClass )
75
+ throws InstantiationException , IllegalAccessException , java .lang .reflect .InvocationTargetException {
76
+
77
+ try {
78
+ return argumentClass .newInstance ();
79
+ }
80
+ catch (Exception e ) {
81
+ // Ignore - should log
82
+ }
83
+
84
+ Constructor [] constructors = argumentClass .getDeclaredConstructors ();
85
+
86
+ if (constructors .length == 0 ) {
87
+ return argumentClass .newInstance ();
88
+ }
89
+
90
+ int i = 0 ;
91
+ Class [] types = constructors [i ].getParameterTypes ();
92
+ Object [] paramValues = new Object [types .length ];
93
+
94
+ for (int j = 0 ; j < types .length ; j ++) {
95
+ if (types [j ].isPrimitive ()) {
96
+ paramValues [j ] = Integer .valueOf (0 ).byteValue ();
97
+ }
98
+ else {
99
+ paramValues [j ] = constructCopy (types [j ]);
100
+ }
101
+ }
102
+ return constructors [i ].newInstance (paramValues );
103
+ }
71
104
}
0 commit comments