-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathReflect.java
More file actions
1300 lines (1182 loc) · 52.1 KB
/
Reflect.java
File metadata and controls
1300 lines (1182 loc) · 52.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
* 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. *
* *
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* *
*****************************************************************************/
package bsh;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.Objects;
import java.util.WeakHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static bsh.This.Keys.BSHTHIS;
import static bsh.This.Keys.BSHSTATIC;
import static bsh.This.Keys.BSHCLASSMODIFIERS;
import static bsh.Capabilities.haveAccessibility;
/**
* All of the reflection API code lies here. It is in the form of static
* utilities. Maybe this belongs in LHS.java or a generic object
* wrapper class.
*
* @author Pat Niemeyer
* @author Daniel Leuck
* @author Nick nickl- Lombard
*/
/*
Note: This class is messy. The method and field resolution need to be
rewritten. Various methods in here catch NoSuchMethod or NoSuchField
exceptions during their searches. These should be rewritten to avoid
having to catch the exceptions. Method lookups are now cached at a high
level so they are less important, however the logic is messy.
*/
public final class Reflect {
public static final Object[] ZERO_ARGS = {};
public static final Class<?>[] ZERO_TYPES = {};
static final String GET_PREFIX = "get";
static final String SET_PREFIX = "set";
static final String IS_PREFIX = "is";
private static final Map<String,String> ACCESSOR_NAMES = new WeakHashMap<>();
private static final Pattern DEFAULT_PACKAGE
= Pattern.compile("[^\\.]+|bsh\\..*");
private static final Pattern PACKAGE_ACCESS;
static {
String packageAccess = Security.getProperty("package.access");
if (null == packageAccess) packageAccess = "null";
String pattern = Stream.of(packageAccess.split(","))
.filter(s -> !s.isEmpty())
.collect(Collectors.joining("|", "(?:", ").*"));
PACKAGE_ACCESS = Pattern.compile(pattern);
}
/** Invoke method on arbitrary object instance. May be static (through the object
* instance) or dynamic. Object may be a bsh scripted object (bsh.This type).
* @return the result of the method call */
public static Object invokeObjectMethod(
Object object, String methodName, Object[] args,
Interpreter interpreter, CallStack callstack,
Node callerInfo) throws EvalError {
// Bsh scripted object
if (object instanceof This && !This.isExposedThisMethod(methodName))
return ((This) object).invokeMethod(
methodName, args, interpreter, callstack, callerInfo,
false/* declaredOnly */);
// Plain Java object, script engine exposed instance and find java method to invoke
BshClassManager bcm = interpreter.getClassManager();
// Flag primitive for overwrites, value/type exposure and recursion loop metigation.
boolean isPrimitive = object instanceof Primitive;
try { // The type exposed to script engine and used for method lookup
Class<?> type = object.getClass();
if (isPrimitive) { // Overwrite methods cosmetically deferred to bsh.Primitive
if (methodName.equals("equals")) return ((Primitive)object).equals(args[0]);
// NULL and VOID remain Primitive the rest are value/primitive type exposed
if (object != Primitive.NULL && object != Primitive.VOID) {
type = ((Primitive)object).getType();
object = Primitive.unwrap(object);
} // Cosmetic Void.TYPE returned while internal type remains bsh.Primitive
if (methodName.equals("getType") || methodName.equals("getClass"))
return (object == Primitive.VOID) ? ((Primitive)object).getType() : type;
} try { // Script engine exposed instance for method lookup and invocation here
Invocable method = resolveExpectedJavaMethod(
bcm, type, object, methodName, args, false);
NameSpace ns = getThisNS(object);
if (null != ns) ns.setNode(callerInfo);
return method.invoke(object, args); // script engine exposed instance call
} catch (ReflectError re) { // Void has overstayed its welcome round about here
if (object == Primitive.VOID) throw new EvalError("Attempt to invoke method: "
+ methodName + "() on undefined", callerInfo, callstack, re);
// Handle primitive method not found. Autoboxing or magic math method lookup.
// Errors gets rolled up, and not found is deferred back to exposed type.
if (isPrimitive && !interpreter.getStrictJava()) try { // mitigate recursion
if (!Types.isNumeric(object)) return invokeObjectMethod( // autobox type
object, methodName, args, interpreter, callstack, callerInfo);
return numericMathMethod( // find magic math method on all numeric types
object, type, methodName, args, interpreter, callstack, callerInfo);
} catch (TargetError te) { throw te; // method found but errored throw it up
} catch (EvalError ee) { /* not found deffered fall through to exposed type */ }
throw new EvalError( // Deferred/unhandled method not found on exposed type
"Error in method invocation: " + re.getMessage(), callerInfo, callstack, re);
} catch (InvocationTargetException e) {
throw targetErrorFromTargetException(e, methodName, callstack, callerInfo);
}
} catch (UtilEvalError e) {
throw e.toEvalError(callerInfo, callstack);
}
}
/** Package scoped target error, extracted as a method, to prevent duplication.
* Due to the two paths leading to method invocation, via BSHMethodInvocation and
* BSHPrimarySuffix, gets consolidated here.
* @return error instance to throw */
static TargetError targetErrorFromTargetException(InvocationTargetException e,
String methodName, CallStack callstack, Node callerInfo) {
String msg = "Method Invocation " + methodName;
Throwable te = e.getCause();
// Try to squeltch the native code stack trace if the exception was caused by
// a reflective call back into the bsh interpreter (e.g. eval() or source()
boolean isNative = true;
if (te instanceof EvalError)
isNative = (te instanceof TargetError) && ((TargetError) te).inNativeCode();
return new TargetError(msg, te, callerInfo, callstack, isNative);
}
/** Determine which math class to call first, based on the floating point flag.
* If the method is not found on the primary class, attempt using alternative.
* Errors and exceptions will abort and get rolled up.
* @return the result of the method call */
private static Object numericMathMethod(Object object, Class<?> type, String methodName,
Object[] args, Interpreter interpreter, CallStack callstack, Node callerInfo)
throws EvalError {
Class<?> mathType = Types.isFloatingpoint(object) ? BigDecimal.class : BigInteger.class;
try {
return invokeMathMethod(mathType,
object, type, methodName, args, interpreter, callstack, callerInfo);
} catch (TargetError te) { // method found but errored lets throw it back up
throw te.reThrow("Method found on " + mathType.getSimpleName() + " but with error");
} catch (EvalError ee) { // method not found try alternative math provider
return invokeMathMethod(
Types.isFloatingpoint(object) ? BigInteger.class : BigDecimal.class,
object, type, methodName, args, interpreter, callstack, callerInfo);
}
}
/** Cast object up to math type, and invoke the math method with the supplied
* arguments. Assess the method return, if mathType, cast return back down to
* return type and complete the magic. Otherwise return non chaining result.
* @return the result of the method call */
private static Object invokeMathMethod(Class<?> mathType, Object object, Class<?> returnType,
String methodName, Object[] args, Interpreter interpreter, CallStack callstack,
Node callerInfo) throws EvalError {
Object retrn = invokeObjectMethod(Primitive.castWrapper(mathType, object),
methodName, args, interpreter, callstack, callerInfo);
if (retrn instanceof Primitive && ((Primitive)retrn).getType() == mathType)
return Primitive.wrap(Primitive.castWrapper(returnType, retrn), returnType);
return retrn;
}
/**
Invoke a method known to be static.
No object instance is needed and there is no possibility of the
method being a bsh scripted method.
*/
public static Object invokeStaticMethod(
BshClassManager bcm, Class<?> clas, String methodName,
Object [] args, Node callerInfo )
throws ReflectError, UtilEvalError,
InvocationTargetException {
Interpreter.debug("invoke static Method");
NameSpace ns = getThisNS(clas);
if (null != ns)
ns.setNode(callerInfo);
Invocable method = resolveExpectedJavaMethod(
bcm, clas, null, methodName, args, true );
return method.invoke(null, args);
}
public static Object getStaticFieldValue(Class<?> clas, String fieldName)
throws UtilEvalError, ReflectError {
return getFieldValue( clas, null, fieldName, true/*onlystatic*/);
}
/**
* Check for a field with the given name in a java object or scripted object
* if the field exists fetch the value, if not check for a property value.
* If neither is found return Primitive.VOID.
*/
public static Object getObjectFieldValue( Object object, String fieldName )
throws UtilEvalError, ReflectError {
if ( object instanceof This ) {
return ((This) object).namespace.getVariable( fieldName );
} else if( object == Primitive.NULL ) {
throw new UtilTargetError( new NullPointerException(
"Attempt to access field '" +fieldName+"' on null value" ) );
} else {
try {
return getFieldValue(
object.getClass(), object, fieldName, false/*onlystatic*/);
} catch ( ReflectError e ) {
// no field, try property access
if ( hasObjectPropertyGetter( object.getClass(), fieldName ) )
return getObjectProperty( object, fieldName );
else
throw e;
}
}
}
static LHS getLHSStaticField(Class<?> clas, String fieldName)
throws UtilEvalError, ReflectError {
try {
Invocable f = resolveExpectedJavaField(
clas, fieldName, true/*onlystatic*/);
return new LHS(f);
} catch ( ReflectError e ) {
NameSpace ns = getThisNS(clas);
if (isGeneratedClass(clas) && null != ns && ns.isClass) {
Variable var = ns.getVariableImpl(fieldName, true);
if ( null != var && (!var.hasModifier("private")
|| haveAccessibility()) )
return new LHS(ns, fieldName);
}
// not a field, try property access
if ( hasObjectPropertySetter( clas, fieldName ) )
return new LHS( clas, fieldName );
else
throw e;
}
}
/**
Get an LHS reference to an object field.
This method also deals with the field style property access.
In the field does not exist we check for a property setter.
*/
static LHS getLHSObjectField( Object object, String fieldName )
throws UtilEvalError, ReflectError {
if ( object instanceof This )
return new LHS( ((This)object).namespace, fieldName, false );
try {
Invocable f = resolveExpectedJavaField(
object.getClass(), fieldName, false/*staticOnly*/ );
return new LHS(object, f);
} catch ( ReflectError e ) {
NameSpace ns = getThisNS(object);
if (isGeneratedClass(object.getClass()) && null != ns && ns.isClass) {
Variable var = ns.getVariableImpl(fieldName, true);
if ( null != var && (!var.hasModifier("private")
|| haveAccessibility()) )
return new LHS(ns, fieldName);
}
// not a field, try property access
if ( hasObjectPropertySetter( object.getClass(), fieldName ) )
return new LHS( object, fieldName );
else
throw e;
}
}
private static Object getFieldValue(
Class<?> clas, Object object, String fieldName, boolean staticOnly)
throws UtilEvalError, ReflectError {
try {
Invocable f = resolveExpectedJavaField(clas, fieldName, staticOnly);
return f.invoke(object);
} catch ( ReflectError e ) {
NameSpace ns = getThisNS(clas);
if (isGeneratedClass(clas) && null != ns && ns.isClass)
if (staticOnly) {
Variable var = ns.getVariableImpl(fieldName, true);
Object val = Primitive.VOID;
if ( null != var && (!var.hasModifier("private")
|| haveAccessibility()) )
val = ns.unwrapVariable(var);
if (Primitive.VOID != val)
return val;
}
else if (null != (ns = getThisNS(object))) {
Variable var = ns.getVariableImpl(fieldName, true);
Object val = Primitive.VOID;
if ( null != var && (!var.hasModifier("private")
|| haveAccessibility()) )
val = ns.unwrapVariable(var);
if (Primitive.VOID != val)
return val;
}
throw e;
} catch(InvocationTargetException e) {
if (e.getCause() instanceof InterpreterError)
throw (InterpreterError)e.getCause();
if (e.getCause() instanceof UtilEvalError)
throw new UtilTargetError(e.getCause());
throw new ReflectError("Can't access field: "
+ fieldName, e.getCause());
}
}
/*
Note: this method and resolveExpectedJavaField should be rewritten
to invert this logic so that no exceptions need to be caught
unecessarily. This is just a temporary impl.
@return the field or null if not found
*/
protected static Invocable resolveJavaField(
Class<?> clas, String fieldName, boolean staticOnly )
throws UtilEvalError {
try {
return resolveExpectedJavaField( clas, fieldName, staticOnly );
} catch ( ReflectError e ) {
return null;
}
}
/**
@throws ReflectError if the field is not found.
*/
/*
Note: this should really just throw NoSuchFieldException... need
to change related signatures and code.
*/
protected static Invocable resolveExpectedJavaField(
Class<?> clas, String fieldName, boolean staticOnly)
throws UtilEvalError, ReflectError {
Invocable field = BshClassManager.memberCache
.get(clas).findField(fieldName);
if (null == field)
throw new ReflectError("No such field: "
+ fieldName + " for class: " + clas.getName());
if ( staticOnly && !field.isStatic() )
throw new UtilEvalError(
"Can't reach instance field: " + fieldName
+ " from static context: " + clas.getName() );
return field;
}
/**
This method wraps resolveJavaMethod() and expects a non-null method
result. If the method is not found it throws a descriptive ReflectError.
*/
protected static Invocable resolveExpectedJavaMethod(
BshClassManager bcm, Class<?> clas, Object object,
String name, Object[] args, boolean staticOnly )
throws ReflectError, UtilEvalError {
if ( object == Primitive.NULL )
throw new UtilTargetError( new NullPointerException(
"Attempt to invoke method " +name+" on null value" ) );
Class<?>[] types = Types.getTypes(args);
Invocable method = resolveJavaMethod( clas, name, types, staticOnly );
if ( null != bcm && bcm.getStrictJava()
&& method != null && method.getDeclaringClass().isInterface()
&& method.getDeclaringClass() != clas
&& Modifier.isStatic(method.getModifiers()))
// static interface methods are class only
method = null;
if ( method == null )
throw new ReflectError(
( staticOnly ? "Static method " : "Method " )
+ StringUtil.methodString(name, types) +
" not found in class'" + clas.getName() + "'");
return method;
}
/**
The full blown resolver method. All other method invocation methods
delegate to this. The method may be static or dynamic unless
staticOnly is set (in which case object may be null).
If staticOnly is set then only static methods will be located.
<p/>
This method performs caching (caches discovered methods through the
class manager and utilizes cached methods.)
<p/>
This method determines whether to attempt to use non-public methods
based on Capabilities.haveAccessibility() and will set the accessibilty
flag on the method as necessary.
<p/>
If, when directed to find a static method, this method locates a more
specific matching instance method it will throw a descriptive exception
analogous to the error that the Java compiler would produce.
Note: as of 2.0.x this is a problem because there is no way to work
around this with a cast.
<p/>
@param staticOnly
The method located must be static, the object param may be null.
@return the method or null if no matching method was found.
*/
protected static Invocable resolveJavaMethod(
Class<?> clas, String name, Class<?>[] types,
boolean staticOnly ) throws UtilEvalError {
if ( clas == null )
throw new InterpreterError("null class");
Invocable method = BshClassManager.memberCache
.get(clas).findMethod(name, types);
Interpreter.debug("resolved java method: ", method, " on class: ", clas);
checkFoundStaticMethod( method, staticOnly, clas );
return method;
}
/** Find a static method member of baseClass, for the given name.
* @param baseClass class to query
* @param methodName method name to find
* @return a BshMethod wrapped Method. */
static BshMethod staticMethodImport(Class<?> baseClass, String methodName) {
Invocable method = BshClassManager.memberCache.get(baseClass)
.findStaticMethod(methodName);
if (null != method)
return new BshMethod(method, null);
return null;
}
/**
Primary object constructor
This method is simpler than those that must resolve general method
invocation because constructors are not inherited.
<p/>
This method determines whether to attempt to use non-public constructors
based on Capabilities.haveAccessibility() and will set the accessibilty
flag on the method as necessary.
<p/>
*/
static Object constructObject( Class<?> clas, Object[] args )
throws ReflectError, InvocationTargetException {
return constructObject(clas, null, args);
}
static Object constructObject( Class<?> clas, Object object, Object[] args )
throws ReflectError, InvocationTargetException {
if ( null == clas )
return Primitive.NULL;
if ( clas.isInterface() )
throw new ReflectError(
"Can't create instance of an interface: "+clas);
Class<?>[] types = Types.getTypes(args);
if (clas.isMemberClass() && !isStatic(clas) && null != object)
types = Stream.concat(Stream.of(object.getClass()),
Stream.of(types)).toArray(Class[]::new);
Interpreter.debug("Looking for most specific constructor: ", clas);
Invocable con = BshClassManager.memberCache.get(clas)
.findMethod(clas.getName(), types);
if ( con == null || (args.length != con.getParameterCount()
&& !con.isVarArgs() && !con.isInnerClass()))
throw cantFindConstructor( clas, types );
try {
return con.invoke( object, args );
} catch(InvocationTargetException e) {
if (e.getCause().getCause() instanceof IllegalAccessException)
throw new ReflectError(
"We don't have permission to create an instance. "
+ e.getCause().getCause().getMessage()
+ " Use setAccessibility(true) to enable access.",
e.getCause().getCause());
throw e;
}
}
/**
* Find the best match for signature idealMatch and return the method.
* This method anticipates receiving the full list of BshMethods of
* the same name, regardless of the potential arity/validity of
* each method.
*
* @param idealMatch the signature to look for
* @param methods the set of candidate {@link BshMethod}s which
* differ only in the types of their arguments.
*/
public static BshMethod findMostSpecificBshMethod(
Class<?>[] idealMatch, List<BshMethod> methods ) {
Interpreter.debug("find most specific BshMethod for: "+
Arrays.toString(idealMatch));
int match = findMostSpecificBshMethodIndex( idealMatch, methods );
return match == -1 ? null : methods.get(match);
}
/**
* Find the best match for signature idealMatch and return the position
* of the matching signature within the list.
* This method anticipates receiving the full list of BshMethods of the
* same name,regardless of the potential arity/validity of each method.
* Filter the list of methods for only valid candidates
* before performing the comparison (e.g. method name and
* number of args match). Also expand the parameter type list
* for VarArgs methods.
*
* @param idealMatch the signature to look for
* @param methods the set of candidate BshMethods which differ only in the
* types of their arguments.
*/
public static int findMostSpecificBshMethodIndex(Class<?>[] idealMatch,
List<BshMethod> methods) {
for (int i=0; i<methods.size(); i++)
Interpreter.debug(" "+i+":"+methods.get(i).toString()+" "+methods.get(i).getClass().getName());
/*
* Filter for non-varArgs method signatures of the same arity
*/
List<Class<?>[]> candidateSigs = new ArrayList<>();
// array to remap the index in the new list
ArrayList<Integer> remap = new ArrayList<>();
int i=0;
for( BshMethod m : methods ) {
Class<?>[] parameterTypes = m.getParameterTypes();
if (idealMatch.length == parameterTypes.length) {
remap.add(i);
candidateSigs.add( parameterTypes );
}
i++;
}
Class<?>[][] sigs = candidateSigs.toArray(new Class[candidateSigs.size()][]);
int match = findMostSpecificSignature( idealMatch, sigs );
if (match >= 0) {
match = remap.get(match);
Interpreter.debug(" remap: "+remap);
Interpreter.debug(" match:"+match);
return match;
}
/*
* If did not get a match then try VarArgs methods
* Filter for varArgs method signatures of sufficient arity
* Expand out the vararg parameters.
*/
candidateSigs.clear();
remap.clear();
i=0;
for( BshMethod m : methods ) {
Class<?>[] parameterTypes = m.getParameterTypes();
if (m.isVarArgs()
&& idealMatch.length >= parameterTypes.length-1 ) {
Class<?>[] candidateSig = new Class[idealMatch.length];
System.arraycopy(parameterTypes, 0, candidateSig, 0,
parameterTypes.length-1);
Class<?> arrayCompType = parameterTypes[parameterTypes.length-1].getComponentType();
Arrays.fill(candidateSig, parameterTypes.length-1,
idealMatch.length, arrayCompType);
remap.add(i);
candidateSigs.add( candidateSig );
}
i++;
}
sigs = candidateSigs.toArray(new Class[candidateSigs.size()][]);
match = findMostSpecificSignature( idealMatch, sigs);
if (match >= 0) {
match = remap.get(match);
Interpreter.debug(" remap (varargs): "+Arrays.toString(remap.toArray(new Integer[0])));
Interpreter.debug(" match (varargs):"+match);
}
return match;
}
/**
* Find the best match for signature idealMatch and return the method.
* This method anticipates receiving the full list of methods of
* the same name, regardless of the potential arity/validity of
* each method.
*
* @param idealMatch the signature to look for
* @param methods the set of candidate {@link Invocable}s which
* differ only in the types of their arguments.
*/
public static Invocable findMostSpecificInvocable(
Class<?>[] idealMatch, List<Invocable> methods ) {
Interpreter.debug("find most specific Invocable for: "+
Arrays.toString(idealMatch));
int match = findMostSpecificInvocableIndex( idealMatch, methods );
return match == -1 ? null : methods.get(match);
}
/**
* Find the best match for signature idealMatch and return the position
* of the matching signature within the list.
* This method anticipates receiving the full list of methods of the
* same name,regardless of the potential arity/validity of each method.
* Filter the list of methods for only valid candidates
* before performing the comparison (e.g. method name and
* number of args match). Also expand the parameter type list
* for VarArgs methods.
*
* This method currently does not take into account Java 5 covariant
* return types... which I think will require that we find the most
* derived return type of otherwise identical best matches.
*
* @param idealMatch the signature to look for
* @param methods the set of candidate method which differ only in the
* types of their arguments.
*/
public static int findMostSpecificInvocableIndex(Class<?>[] idealMatch,
List<Invocable> methods) {
for (int i=0; i<methods.size(); i++)
Interpreter.debug(" "+i+"="+methods.get(i).toString());
/*
* Filter for non-varArgs method signatures of the same arity
*/
List<Class<?>[]> candidateSigs = new ArrayList<>();
// array to remap the index in the new list
ArrayList<Integer> remap = new ArrayList<>();
int i=0;
for( Invocable method : methods ) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (idealMatch.length == parameterTypes.length) {
remap.add(i);
candidateSigs.add( parameterTypes );
}
i++;
}
Class<?>[][] sigs = candidateSigs.toArray(new Class[candidateSigs.size()][]);
int match = findMostSpecificSignature( idealMatch, sigs );
if (match >= 0) {
match = remap.get(match);
Interpreter.debug(" remap="+Arrays.toString(remap.toArray(new Integer[0])));
Interpreter.debug(" match="+match);
return match;
}
/*
* If did not get a match then try VarArgs methods
* Filter for varArgs method signatures of sufficient arity
*/
candidateSigs.clear();
remap.clear();
i=0;
for( Invocable method : methods ) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (method.isVarArgs()
&& idealMatch.length >= parameterTypes.length-1 ) {
Class<?>[] candidateSig = new Class[idealMatch.length];
System.arraycopy(parameterTypes, 0, candidateSig, 0,
parameterTypes.length-1);
Arrays.fill(candidateSig, parameterTypes.length-1,
idealMatch.length, method.getVarArgsComponentType());
remap.add(i);
candidateSigs.add( candidateSig );
}
i++;
}
sigs = candidateSigs.toArray(new Class[candidateSigs.size()][]);
match = findMostSpecificSignature( idealMatch, sigs);
/*
* return the remaped value so that the index is relative
* to the original list
*/
if (match >= 0)
match = remap.get(match);
Interpreter.debug(" remap (varargs) ="+Arrays.toString(remap.toArray(new Integer[0])));
Interpreter.debug(" match (varargs) ="+match);
return match;
}
/**
Implement JLS 15.11.2
Return the index of the most specific arguments match or -1 if no
match is found.
This method is used by both methods and constructors (which
unfortunately don't share a common interface for signature info).
@return the index of the most specific candidate
*/
/*
Note: Two methods which are equally specific should not be allowed by
the Java compiler. In this case BeanShell currently chooses the first
one it finds. We could add a test for this case here (I believe) by
adding another isSignatureAssignable() in the other direction between
the target and "best" match. If the assignment works both ways then
neither is more specific and they are ambiguous. I'll leave this test
out for now because I'm not sure how much another test would impact
performance. Method selection is now cached at a high level, so a few
friendly extraneous tests shouldn't be a problem.
*/
static int findMostSpecificSignature(
Class<?>[] idealMatch, Class<?>[][] candidates ) {
for ( int round = Types.FIRST_ROUND_ASSIGNABLE;
round <= Types.LAST_ROUND_ASSIGNABLE; round++ ) {
Class<?>[] bestMatch = null;
int bestMatchIndex = -1;
for (int i=0; i < candidates.length; i++) {
Class<?>[] targetMatch = candidates[i];
if (null != bestMatch && Types
.areSignaturesEqual(targetMatch, bestMatch))
// overridden keep first
continue;
// If idealMatch fits targetMatch and this is the first match
// or targetMatch is more specific than the best match, make it
// the new best match.
if ( Types.isSignatureAssignable(
idealMatch, targetMatch, round )
&& ( bestMatch == null
|| Types.areSignaturesEqual(idealMatch, targetMatch)
|| ( Types.isSignatureAssignable(targetMatch, bestMatch,
Types.JAVA_BASE_ASSIGNABLE)
&& !Types.areSignaturesEqual(idealMatch, bestMatch)))) {
bestMatch = targetMatch;
bestMatchIndex = i;
}
}
if ( bestMatch != null )
return bestMatchIndex;
}
return -1;
}
static String accessorName( String prefix, String propName ) {
if (!ACCESSOR_NAMES.containsKey(propName)) {
char[] ch = propName.toCharArray();
ch[0] = Character.toUpperCase(ch[0]);
ACCESSOR_NAMES.put(propName, new String(ch));
}
return prefix + ACCESSOR_NAMES.get(propName);
}
public static boolean hasObjectPropertyGetter(
Class<?> clas, String propName ) {
if ( Types.isPropertyType(clas) )
return true;
return BshClassManager.memberCache
.get(clas).hasMember(propName)
&& null != BshClassManager.memberCache
.get(clas).findGetter(propName);
}
public static boolean hasObjectPropertySetter(
Class<?> clas, String propName ) {
if ( Types.isPropertyType(clas) )
return true;
return BshClassManager.memberCache
.get(clas).hasMember(propName)
&& null != BshClassManager.memberCache
.get(clas).findSetter(propName);
}
@SuppressWarnings("rawtypes")
public static Object getObjectProperty(Object obj, String propName) {
if (Types.isPropertyTypeEntry(obj)) switch (propName) {
case "key":
return ((Entry) obj).getKey();
case "val": case "value":
return ((Entry) obj).getValue();
}
return getObjectProperty(obj, (Object) propName);
}
@SuppressWarnings("rawtypes")
public static Object getObjectProperty(Object obj, Object propName) {
if ( Types.isPropertyTypeMap(obj) ) {
Map map = (Map) obj;
if (map.containsKey(propName))
return map.get(propName);
return Primitive.VOID;
}
if ( Types.isPropertyTypeEntry(obj) ) {
Entry entre = (Entry) obj;
if (propName.equals(entre.getKey()))
return entre.getValue();
return Primitive.VOID;
}
Class<?> cls = obj.getClass();
if ( Types.isPropertyTypeEntryList(cls) ) {
Entry entre = getEntryForKey(propName, (Entry[]) obj);
if ( null != entre )
return entre.getValue();
return Primitive.VOID;
}
if ( obj instanceof Class )
cls = (Class) obj;
Invocable getter = BshClassManager.memberCache.get(cls)
.findGetter(propName.toString());
if ( null == getter ) {
Interpreter.debug("property getter not found");
return Primitive.VOID;
}
try {
return getter.invoke(obj);
} catch(InvocationTargetException e) {
Interpreter.debug("Property accessor threw exception");
return Primitive.VOID;
}
}
@SuppressWarnings("rawtypes")
public static Entry getEntryForKey(Object key, Entry[] entries) {
for ( Entry ntre : entries )
if ( key.equals(ntre.getKey()) )
return ntre;
return null;
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Object setObjectProperty(
Object obj, String propName, Object value) {
if (Types.isPropertyTypeEntry(obj)) switch(propName) {
case "val": case "value":
return ((Entry) obj).setValue(value);
}
return setObjectProperty(obj, (Object) propName, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Object setObjectProperty(
Object obj, Object propName, Object value) {
if ( Types.isPropertyTypeMap(obj) )
return ((Map) obj).put(propName, Primitive.unwrap(value));
if ( Types.isPropertyTypeEntry(obj) ) {
Entry entre = (Entry) obj;
if ( propName.equals(entre.getKey()) )
return entre.setValue(Primitive.unwrap(value));
throw new ReflectError("No such property setter: " + propName
+ " for type: " + StringUtil.typeString(obj));
}
Class<?> cls = obj.getClass();
if ( Types.isPropertyTypeEntryList(cls) )
return getEntryForKey(propName, (Entry[]) obj)
.setValue(Primitive.unwrap(value));
if ( obj instanceof Class )
cls = (Class) obj;
Invocable setter = BshClassManager.memberCache.get(cls)
.findSetter(propName.toString());
if ( null == setter )
throw new ReflectError("No such property setter: " + propName
+ " for type: " + StringUtil.typeString(cls));
try {
return setter.invoke(obj, new Object[] { Primitive.unwrap(value) });
} catch(InvocationTargetException e) {
throw new ReflectError("Property accessor threw exception: "
+ e.getCause(), e.getCause());
}
}
/**
A command may be implemented as a compiled Java class containing one or
more static invoke() methods of the correct signature. The invoke()
methods must accept two additional leading arguments of the interpreter
and callstack, respectively. e.g. invoke(interpreter, callstack, ... )
This method adds the arguments and invokes the static method, returning
the result.
*/
public static Object invokeCompiledCommand(
Class<?> commandClass, Object [] args, Interpreter interpreter,
CallStack callstack, Node callerInfo )
throws UtilEvalError
{
// add interpereter and namespace to args list
Object[] invokeArgs = new Object[args.length + 2];
invokeArgs[0] = interpreter;
invokeArgs[1] = callstack;
System.arraycopy( args, 0, invokeArgs, 2, args.length );
BshClassManager bcm = interpreter.getClassManager();
try {
return invokeStaticMethod(
bcm, commandClass, "invoke", invokeArgs, callerInfo );
} catch ( InvocationTargetException e ) {
throw new UtilEvalError(
"Error in compiled command: " + e.getCause(), e );
} catch ( ReflectError e ) {
throw new UtilEvalError("Error invoking compiled command: " + e, e );
}
}
static void logInvokeMethod(String msg, Invocable method, List<Object> params) {
if (Interpreter.DEBUG.get()) {
logInvokeMethod(msg, method, params.toArray());
}
}
static void logInvokeMethod(String msg, Invocable method, Object[] args) {
if (Interpreter.DEBUG.get()) {
Interpreter.debug(msg, method, " with args:");
for (int i = 0; i < args.length; i++) {
final Object arg = args[i];
Interpreter.debug("args[", i, "] = ", arg, " type = ", (arg == null ? "<unknown>" : arg.getClass()));
}
}
}
private static void checkFoundStaticMethod(
Invocable method, boolean staticOnly, Class<?> clas )
throws UtilEvalError
{
// We're looking for a static method but found an instance method
if ( method != null && staticOnly && !method.isStatic() )
throw new UtilEvalError(
"Cannot reach instance method: "
+ StringUtil.methodString(
method.getName(), method.getParameterTypes() )
+ " from static context: "+ clas.getName() );
}
private static ReflectError cantFindConstructor(
Class<?> clas, Class<?>[] types )
{
if ( types.length == 0 )
return new ReflectError(
"Can't find default constructor for: "+clas);
else
return new ReflectError(
"Can't find constructor: "
+ StringUtil.methodString( clas.getName(), types )
+" in class: "+ clas.getName() );
}
/*
* Whether class is a bsh script generated type
*/
public static boolean isGeneratedClass(Class<?> type) {
return null != type && type != GeneratedClass.class
&& GeneratedClass.class.isAssignableFrom(type);
}
/**
* Get the static bsh namespace field from the class.
* @param className may be the name of clas itself or a superclass of clas.
*/
public static This getClassStaticThis(Class<?> clas, String className) {
try {
return (This) getStaticFieldValue(clas, BSHSTATIC + className);
} catch (Exception e) {
throw new InterpreterError("Unable to get class static space: " + e, e);
}
}
/**
* Get the instance bsh namespace field from the object instance.
* @return the class instance This object or null if the object has not
* been initialized.
*/
public static This getClassInstanceThis(Object instance, String className) {
try {
Object o = getObjectFieldValue(instance, BSHTHIS + className);
return (This) Primitive.unwrap(o); // unwrap Primitive.Null to null
} catch (Exception e) {
throw new InterpreterError("Generated class: Error getting This " + e, e);
}
}