3
3
import com .annimon .ownlang .lib .*;
4
4
import com .annimon .ownlang .modules .Module ;
5
5
import java .lang .reflect .Array ;
6
+ import java .lang .reflect .Constructor ;
6
7
import java .lang .reflect .Field ;
7
8
import java .lang .reflect .InvocationTargetException ;
8
9
import java .lang .reflect .Method ;
@@ -156,17 +157,13 @@ private Value asSubclass(Value... args) {
156
157
return new ClassValue (clazz .asSubclass ( ((ClassValue )args [0 ]).clazz ));
157
158
}
158
159
159
- private Value isAssignableFrom (Value ... args ) {
160
+ private Value isAssignableFrom (Value [] args ) {
160
161
Arguments .check (1 , args .length );
161
162
return NumberValue .fromBoolean (clazz .isAssignableFrom ( ((ClassValue )args [0 ]).clazz ));
162
163
}
163
164
164
- private Value newInstance (Value ... args ) {
165
- try {
166
- return new ObjectValue (clazz .newInstance ());
167
- } catch (InstantiationException | IllegalAccessException ex ) {
168
- return NULL ;
169
- }
165
+ private Value newInstance (Value [] args ) {
166
+ return findConstructorAndInstantiate (args , clazz .getConstructors ());
170
167
}
171
168
172
169
private Value cast (Value ... args ) {
@@ -293,6 +290,21 @@ private static Value getValue(Class<?> clazz, Object object, String key) {
293
290
294
291
return NULL ;
295
292
}
293
+
294
+ private static Value findConstructorAndInstantiate (Value [] args , Constructor <?>[] ctors ) {
295
+ for (Constructor <?> ctor : ctors ) {
296
+ if (ctor .getParameterCount () != args .length ) continue ;
297
+ if (!isMatch (args , ctor .getParameterTypes ())) continue ;
298
+ try {
299
+ final Object result = ctor .newInstance (valuesToObjects (args ));
300
+ return new ObjectValue (result );
301
+ } catch (InstantiationException | IllegalAccessException
302
+ | IllegalArgumentException | InvocationTargetException ex ) {
303
+ // skip
304
+ }
305
+ }
306
+ return null ;
307
+ }
296
308
297
309
private static Function methodsToFunction (Object object , List <Method > methods ) {
298
310
return (args ) -> {
@@ -312,7 +324,7 @@ private static Function methodsToFunction(Object object, List<Method> methods) {
312
324
return null ;
313
325
};
314
326
}
315
-
327
+
316
328
private static boolean isMatch (Value [] args , Class <?>[] types ) {
317
329
for (int i = 0 ; i < args .length ; i ++) {
318
330
final Value arg = args [i ];
0 commit comments