/
MethodUtil.java
2565 lines (2181 loc) · 83.2 KB
/
MethodUtil.java
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
/*Copyright ©2019 TommyLemon(https://github.com/TommyLemon/UnitAuto)
Licensed 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.*/
package unitauto;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.*;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.ChronoLocalDateTime;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeoutException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.util.TypeUtils;
/**方法/函数的工具类,扫描方法列表、反射执行方法等
* @author Lemon
*/
public class MethodUtil {
public static final String TAG = "MethodUtil";
/**监听器
* @param <T>
*/
public interface Listener<T> {
/**结束回调
* @param data
* @param method
* @param proxy
* @param extras
* @throws Exception
*/
void complete(T data, Method method, InterfaceProxy proxy, Object... extras) throws Exception;
/**结束回调
*/
default void complete(T data) throws Exception {
complete(data, null, null);
}
/**前置事件,准备数据等
* @param instance
* @param method
* @param types
* @param args
* @param proxy
* @param extras
* @return
* @throws Exception
*/
default Boolean beforeCall(Object instance, Method method, Class<?>[] types, Object[] args, InterfaceProxy proxy, Object... extras) throws Exception {
return null;
}
/**后置事件,清理数据,恢复现场等
* @param returnValue
* @param instance
* @param method
* @param types
* @param args
* @param proxy
* @param extras
* @return
* @throws Exception
*/
default Object afterCall(Object returnValue, Object instance, Method method, Class<?>[] types, Object[] args, InterfaceProxy proxy, Object... extras) throws Exception {
return returnValue;
}
}
/**实例获取器
*/
public interface InstanceGetter {
/**获取实例
* @param clazz
* @param classArgs
* @param reuse true - 复用现有的实例;false - new 出实例;null - 环境相关类都默认 true,其它类都默认 false
* @return
* @throws Exception
*/
Object getInstance(@NotNull Class<?> clazz, List<Argument> classArgs, Boolean reuse) throws Exception;
/**获取实例
* @param clazz
* @param classArgs
* @return
* @throws Exception
*/
default Object getInstance(@NotNull Class<?> clazz, List<Argument> classArgs) throws Exception {
return getInstance(clazz, classArgs, null);
}
/**前置事件,准备依赖等
* @param clazz
* @param classArgs
* @param reuse
* @return
* @throws Exception
*/
default Boolean beforeGet(@NotNull Class<?> clazz, List<Argument> classArgs, Boolean reuse) throws Exception {
return null;
}
/**后置事件,调整实例值等
* @param instance
* @param clazz
* @param classArgs
* @param reuse
* @return
* @throws Exception
*/
default Object afterGet(Object instance, @NotNull Class<?> clazz, List<Argument> classArgs, Boolean reuse) throws Exception {
return instance;
}
}
/**JSON 回调
*/
public interface JSONCallback {
/**新建成功结果
* @return
*/
JSONObject newSuccessResult();
/**新建失败结果
* @param e
* @return
*/
JSONObject newErrorResult(Throwable e);
/**将其它类型 value 转为 JSONObject 实例
* @param type
* @param value
* @return
*/
JSONObject parseJSON(String type, Object value);
}
/**类加载回调
*/
public interface ClassLoaderCallback {
/**加载类
* @param packageOrFileName
* @param className
* @param ignoreError
* @return
* @throws ClassNotFoundException
* @throws IOException
*/
Class<?> loadClass(String packageOrFileName, String className, boolean ignoreError) throws ClassNotFoundException, IOException;
/**加载类列表
* @param packageOrFileName
* @param className
* @param ignoreError
* @param limit
* @param offset
* @return
* @throws ClassNotFoundException
* @throws IOException
*/
List<Class<?>> loadClassList(String packageOrFileName, String className, boolean ignoreError, int limit, int offset) throws ClassNotFoundException, IOException;
/**加载类列表
* @param packageOrFileName
* @param className
* @param ignoreError
* @return
* @throws ClassNotFoundException
* @throws IOException
*/
default List<Class<?>> loadClassList(String packageOrFileName, String className, boolean ignoreError) throws ClassNotFoundException, IOException {
return loadClassList(packageOrFileName, className, ignoreError, 0, 0);
}
}
public static String KEY_CODE = "code";
public static String KEY_MSG = "msg";
public static int CODE_SUCCESS = 200;
public static int CODE_SERVER_ERROR = 500;
public static String MSG_SUCCESS = "success";
public static String KEY_REUSE = "reuse";
public static String KEY_UI = "ui";
public static String KEY_TIME = "time";
public static String KEY_TIMEOUT = "timeout";
public static String KEY_PACKAGE = "package";
public static String KEY_THIS = "this";
public static String KEY_CLASS = "class";
public static String KEY_CONSTRUCTOR = "constructor";
public static String KEY_TYPE = "type";
public static String KEY_VALUE = "value";
public static String KEY_WARN = "warn";
public static String KEY_STATIC = "static";
public static String KEY_NAME = "name";
public static String KEY_METHOD = "method";
public static String KEY_TRACE = "trace";
public static String KEY_MOCK = "mock";
public static String KEY_QUERY = "query";
public static String KEY_RETURN = "return";
public static String KEY_TIME_DETAIL = "time:start|duration|end";
public static String KEY_CLASS_ARGS = "classArgs";
public static String KEY_METHOD_ARGS = "methodArgs";
public static String KEY_ARGS = "args";
public static String KEY_CALLBACK = "callback";
public static String KEY_GLOBAL = "global";
public static String KEY_CALL_LIST = "call()[]";
public static String KEY_CALL_MAP = "call(){}";
public static String KEY_PACKAGE_TOTAL = "packageTotal";
public static String KEY_CLASS_TOTAL = "classTotal";
public static String KEY_METHOD_TOTAL = "methodTotal";
public static String KEY_PACKAGE_LIST = "packageList";
public static String KEY_CLASS_LIST = "classList";
public static String KEY_METHOD_LIST = "methodList";
//不能在 static 代码块赋值,否则 MethodUtil 子类中 static 代码块对它赋值的代码不会执行!
@NotNull
public static InstanceGetter INSTANCE_GETTER = new InstanceGetter() {
@Override
public Object getInstance(@NotNull Class<?> clazz, List<Argument> classArgs, Boolean reuse) throws Exception {
return getInvokeInstance(clazz, classArgs, reuse);
}
};
//不能在 static 代码块赋值,否则 MethodUtil 子类中 static 代码块对它赋值的代码不会执行!
@NotNull
public static ClassLoaderCallback CLASS_LOADER_CALLBACK = new ClassLoaderCallback() {
public Class<?> loadClass(String packageOrFileName, String className, boolean ignoreError) throws ClassNotFoundException ,IOException {
return findClass(packageOrFileName, className, ignoreError);
};
@Override
public List<Class<?>> loadClassList(String packageOrFileName, String className, boolean ignoreError, int limit, int offset)
throws ClassNotFoundException, IOException {
return findClassList(packageOrFileName, className, ignoreError, limit, offset);
}
};
//不能在 static 代码块赋值,否则 MethodUtil 子类中 static 代码块对它赋值的代码不会执行!
@NotNull
public static JSONCallback JSON_CALLBACK = new JSONCallback() {
@Override
public JSONObject newSuccessResult() {
return MethodUtil.newSuccessResult();
}
@Override
public JSONObject newErrorResult(Throwable e) {
return MethodUtil.newErrorResult(e);
}
public JSONObject parseJSON(String type, Object value) {
return MethodUtil.parseJSON(type, value);
}
};
@NotNull
public static Map<Class<?>, InterfaceProxy> GLOBAL_CALLBACK_MAP;
// Map<class, <constructorArgs, instance>>
public static final Map<Class<?>, Map<Object, Object>> INSTANCE_MAP;
public static final Map<String, Class<?>> PRIMITIVE_CLASS_MAP;
public static final Map<String, Class<?>> BASE_CLASS_MAP;
public static final Map<String, Class<?>> CLASS_MAP;
public static final Map<Class<?>, Object> DEFAULT_TYPE_VALUE_MAP;
static {
GLOBAL_CALLBACK_MAP = new HashMap<>();
INSTANCE_MAP = new HashMap<>();
PRIMITIVE_CLASS_MAP = new HashMap<String, Class<?>>();
BASE_CLASS_MAP = new HashMap<String, Class<?>>();
CLASS_MAP = new HashMap<String, Class<?>>();
PRIMITIVE_CLASS_MAP.put(boolean.class.getSimpleName(), boolean.class);
PRIMITIVE_CLASS_MAP.put(int.class.getSimpleName(), int.class);
PRIMITIVE_CLASS_MAP.put(long.class.getSimpleName(), long.class);
PRIMITIVE_CLASS_MAP.put(float.class.getSimpleName(), float.class);
PRIMITIVE_CLASS_MAP.put(double.class.getSimpleName(), double.class);
BASE_CLASS_MAP.putAll(PRIMITIVE_CLASS_MAP);
BASE_CLASS_MAP.put(Boolean.class.getSimpleName(), Boolean.class);
BASE_CLASS_MAP.put(Integer.class.getSimpleName(), Integer.class);
BASE_CLASS_MAP.put(Long.class.getSimpleName(), Long.class);
BASE_CLASS_MAP.put(Float.class.getSimpleName(), Float.class);
BASE_CLASS_MAP.put(Double.class.getSimpleName(), Double.class);
BASE_CLASS_MAP.put(Number.class.getSimpleName(), Number.class);
BASE_CLASS_MAP.put(String.class.getSimpleName(), String.class);
BASE_CLASS_MAP.put(Object.class.getSimpleName(), Object.class);
CLASS_MAP.putAll(BASE_CLASS_MAP);
CLASS_MAP.put(boolean[].class.getSimpleName(), boolean[].class);
CLASS_MAP.put(int[].class.getSimpleName(), int[].class);
CLASS_MAP.put(long[].class.getSimpleName(), long[].class);
CLASS_MAP.put(float[].class.getSimpleName(), float[].class);
CLASS_MAP.put(double[].class.getSimpleName(), double[].class);
CLASS_MAP.put(Array.class.getSimpleName(), Array.class);
CLASS_MAP.put(Boolean[].class.getSimpleName(), Boolean[].class);
CLASS_MAP.put(Integer[].class.getSimpleName(), Integer[].class);
CLASS_MAP.put(Long[].class.getSimpleName(), Long[].class);
CLASS_MAP.put(Float[].class.getSimpleName(), Float[].class);
CLASS_MAP.put(Double[].class.getSimpleName(), Double[].class);
CLASS_MAP.put(Number[].class.getSimpleName(), Number[].class);
CLASS_MAP.put(String[].class.getSimpleName(), String[].class);
CLASS_MAP.put(Object[].class.getSimpleName(), Object[].class);
CLASS_MAP.put(Array[].class.getSimpleName(), Array[].class);
CLASS_MAP.put(Collection.class.getSimpleName(), Collection.class);//不允许指定<T>
CLASS_MAP.put(AbstractCollection.class.getSimpleName(), AbstractCollection.class);//不允许指定<T>
CLASS_MAP.put(List.class.getSimpleName(), List.class);//不允许指定<T>
CLASS_MAP.put(AbstractList.class.getSimpleName(), AbstractList.class);//不允许指定<T>
CLASS_MAP.put(ArrayList.class.getSimpleName(), ArrayList.class);//不允许指定<T>
CLASS_MAP.put(AbstractSequentialList.class.getSimpleName(), AbstractSequentialList.class);//不允许指定<T>
CLASS_MAP.put(LinkedList.class.getSimpleName(), LinkedList.class);//不允许指定<T>
CLASS_MAP.put(Vector.class.getSimpleName(), Vector.class);//不允许指定<T>
CLASS_MAP.put(Stack.class.getSimpleName(), Stack.class);//不允许指定<T>
CLASS_MAP.put(Queue.class.getSimpleName(), Queue.class);//不允许指定<T>
CLASS_MAP.put(AbstractQueue.class.getSimpleName(), AbstractQueue.class);//不允许指定<T>
CLASS_MAP.put(Deque.class.getSimpleName(), Deque.class);//不允许指定<T>
CLASS_MAP.put(Map.class.getSimpleName(), Map.class);//不允许指定<T>
CLASS_MAP.put(AbstractMap.class.getSimpleName(), AbstractMap.class);//不允许指定<T>
CLASS_MAP.put(HashMap.class.getSimpleName(), HashMap.class);//不允许指定<T>
CLASS_MAP.put(LinkedHashMap.class.getSimpleName(), LinkedHashMap.class);//不允许指定<T>
CLASS_MAP.put(SortedMap.class.getSimpleName(), SortedMap.class);//不允许指定<T>
CLASS_MAP.put(NavigableMap.class.getSimpleName(), NavigableMap.class);//不允许指定<T>
CLASS_MAP.put(TreeMap.class.getSimpleName(), TreeMap.class);//不允许指定<T>
CLASS_MAP.put(Set.class.getSimpleName(), Set.class);//不允许指定<T>
CLASS_MAP.put(AbstractSet.class.getSimpleName(), AbstractSet.class);//不允许指定<T>
CLASS_MAP.put(HashSet.class.getSimpleName(), HashSet.class);//不允许指定<T>
CLASS_MAP.put(LinkedHashSet.class.getSimpleName(), LinkedHashSet.class);//不允许指定<T>
CLASS_MAP.put(SortedSet.class.getSimpleName(), SortedSet.class);//不允许指定<T>
CLASS_MAP.put(NavigableSet.class.getSimpleName(), NavigableSet.class);//不允许指定<T>
CLASS_MAP.put(TreeSet.class.getSimpleName(), TreeSet.class);//不允许指定<T>
CLASS_MAP.put(JSON.class.getSimpleName(), JSON.class);//必须有,Map中没有getLongValue等方法
CLASS_MAP.put(JSONObject.class.getSimpleName(), JSONObject.class);//必须有,Map中没有getLongValue等方法
CLASS_MAP.put(JSONArray.class.getSimpleName(), JSONArray.class);//必须有,Collection中没有getJSONObject等方法
DEFAULT_TYPE_VALUE_MAP = new HashMap<>();
}
/**获取方法列表
* @param request :
{
"mock": true,
"query": 0, // 0-数据,1-总数,2-全部
"package": "apijson.demo.server",
"class": "DemoFunction",
"method": "plus",
"types": ["Integer", "String", "com.alibaba.fastjson.JSONObject"]
//不返回的话,这个接口没意义 "return": true, //返回 class list,方便调试
}
* @return
*/
public static JSONObject listMethod(String request) {
JSONObject result;
try {
JSONObject req = parseObject(request);
if (req == null) {
req = new JSONObject(true);
}
int query = req.getIntValue(KEY_QUERY);
boolean mock = req.getBooleanValue(KEY_MOCK);
String pkgName = req.getString(KEY_PACKAGE);
String clsName = req.getString(KEY_CLASS);
String methodName = req.getString(KEY_METHOD);
JSONArray methodArgTypes = null;
boolean allMethod = isEmpty(methodName, true);
Class<?>[] argTypes = null;
if (allMethod == false) {
methodArgTypes = req.getJSONArray("types");
if (methodArgTypes != null && methodArgTypes.isEmpty() == false) {
argTypes = new Class<?>[methodArgTypes.size()];
for (int i = 0; i < methodArgTypes.size(); i++) {
argTypes[i] = getType(methodArgTypes.getString(i), null, true);
}
}
}
JSONObject obj = getMethodListGroupByClass(pkgName, clsName, methodName, argTypes, query, mock);
result = JSON_CALLBACK.newSuccessResult();
result.putAll(obj); //序列化 Class 只能拿到 name result.put("Class[]", JSON.parseArray(JSON.toJSONString(classlist)));
}
catch (Throwable e) {
e.printStackTrace();
result = JSON_CALLBACK.newErrorResult(e);
}
return result;
}
/**执行方法
* @param request
* @param instance
* @return {@link #invokeMethod(JSONObject, Object, Listener<JSONObject>)}
* @throws Exception
*/
public static void invokeMethod(String request, Object instance, Listener<JSONObject> listener) throws Exception {
invokeMethod(parseObject(request), instance, listener);
}
/**执行方法
* @param req :
{
"static": false, //是否为静态方法,false 时可能会用 constructor & classArgs 来初始化一个类的实例或用 this 直接反序列化成一个类的实例
"ui": false, //放 UI 线程执行,仅 Android 可用
"timeout": 0, //超时时间
"package": "apijson.demo.server", //被测方法所在的包名
"class": "DemoFunction", //被测方法所在的类名
"constructor": "getInstance", //如果是类似单例模式的类,不能用默认构造方法,可以自定义获取实例的方法,传参仍用 classArgs
"classArgs": [ //构造方法的参数值,可以和 methodArgs 结构一样。这里用了简化形式,只传值不传类型,注意简化形式只能在所有值完全符合构造方法的类型定义时才可用
null,
null,
0,
null
],
"this": { //当前类示例,和 constructor & classArgs 二选一
"type": "apijson.demo.server.model.User", //不可缺省,且必须全称
"value": { //User 的示例值,会根据 type 来转为 Java 类型,这里执行等价于 JSON.parseObject(JSON.toJSONString(value), User.class)
"id": 1,
"name": "Tommy"
}
},
"method": "plus", //被测方法名
"methodArgs": [ //被测方法的参数值
{
"type": "Integer", //Boolean, Integer, Number, String, JSONObject, JSONArray 都可缺省,自动根据 value 来判断
"value": 1
},
{
"type": "String", //可缺省,自动根据 value 来判断
"value": "APIJSON"
},
{
"type": "JSONObject", //可缺省,JSONObject 已缓存到 CLASS_MAP,也可以写全称 com.alibaba.fastjson.JSONObject
"value": {}
},
{
"type": "int[]", //不可缺省,且必须全称
"value": [1, 2, 3]
},
{
"type": "java.util.List<apijson.demo.server.model.User>", //不可缺省,且必须全称
"value": [ //TODO 未验证,可能需要解析 type,改用 JSON.parseArray(JSON.toJSONString(value), User.class),或遍历和递归子项来逐个用 cast
{ //apijson.demo.server.model.User
"id": 1,
"name": "Tommy"
},
{ //apijson.demo.server.model.User
"id": 2,
"name": "Lemon"
}
]
},
{
"type": "android.content.Context", //不可缺省,且必须全称
"reuse": true //复用实例池 INSTANCE_MAP 里的
},
{
"type": "unitauto.test.TestUtil$Callback", //interface 示例,注意内部类用 $ 隔开外部类名和内部类名
"value": {
"setData(D)": { //回调方法签名
"callback": true //设置为最终回调方法,会自动等待它被调用,并自动记录回调的时间点和传入参数值
}
}
}
]
}
* @param instance 默认自动 new,传非 null 值一般是因为 Spring 自动注入的 Service, Component, Mapper 等不能自己 new
* @return
* @throws Exception
*/
public static void invokeMethod(JSONObject req, Object instance, Listener<JSONObject> listener) throws Exception {
if (req == null) {
req = new JSONObject(true);
}
String pkgName = req.getString(KEY_PACKAGE);
String clsName = req.getString(KEY_CLASS);
String cttName = req.getString(KEY_CONSTRUCTOR);
String methodName = req.getString(KEY_METHOD);
Boolean trace = req.getBoolean(KEY_TRACE);
long startTime = System.currentTimeMillis();
try {
// 客户端才用 boolean ui = req.getBooleanValue(KEY_UI);
final boolean static_ = req.getBooleanValue(KEY_STATIC); // TODO Boolean static_ = null 时自动根据 Modifier.isStatic 判断?
final long timeout = req.getLongValue(KEY_TIMEOUT);
Object this_ = req.get(KEY_THIS);
List<Argument> clsArgs = getArgList(req, KEY_CLASS_ARGS);
List<Argument> methodArgs = getArgList(req, KEY_METHOD_ARGS);
List<Argument> args_ = getArgList(req, KEY_ARGS);
if (methodArgs != null && args_ != null) {
throw new UnsupportedOperationException(KEY_METHOD_ARGS + " 和 " + KEY_ARGS + " 不能都传,最多传一个!");
}
if (methodArgs == null) {
methodArgs = args_;
}
Class<?> clazz = getInvokeClass(pkgName, clsName);
if (clazz == null) {
throw new ClassNotFoundException("找不到 " + pkgName + "." + clsName + " 对应的类!");
}
if (this_ != null) {
if (StringUtil.isNotEmpty(cttName, true) || clsArgs != null) {
throw new IllegalArgumentException(KEY_THIS + " 与 " + KEY_CONSTRUCTOR + ", " + KEY_CLASS_ARGS + " 两个都不能同时传!");
}
JSONObject obj = new JSONObject();
obj.put(KEY_METHOD_ARGS, Arrays.asList(this_));
List<Argument> mArgs = getArgList(obj, KEY_METHOD_ARGS);
Class<?>[] types = new Class<?>[1];
Object[] args = new Object[1];
initTypesAndValues(mArgs, types, args, true, true);
instance = args[0];
}
if (instance == null && static_ == false) {
Boolean reuse = req.getBoolean(KEY_REUSE);
Boolean b = INSTANCE_GETTER.beforeGet(clazz, clsArgs, reuse);
if (b == null || b == false) {
if (StringUtil.isEmpty(cttName, true)) {
instance = INSTANCE_GETTER.getInstance(clazz, clsArgs, reuse);
} else {
instance = getInvokeResult(clazz, null, cttName, clsArgs, null, null);
}
}
instance = INSTANCE_GETTER.afterGet(instance, clazz, clsArgs, reuse);
}
if (timeout < 0 || timeout > 60000) {
throw new IllegalArgumentException("参数 " + KEY_TIMEOUT + " 的值不合法!只能在 [0, 60000] 范围内!");
}
if (timeout > 0) {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
try {
timer.cancel();
}
catch (Throwable e) {
e.printStackTrace();
}
completeWithError(pkgName, clsName, methodName, startTime, new TimeoutException("处理超时,应该在期望时间 " + timeout + "ms 内!"), listener, trace);
}
}, timeout, Long.MAX_VALUE);
}
InterfaceProxy globalInterfaceProxy = GLOBAL_CALLBACK_MAP.get(clazz);
boolean hasGlobalCallback = globalInterfaceProxy != null;
// if (globalInterfaceProxy == null) {
Set<Entry<String, Object>> set = req.entrySet();
for (Entry<String, Object> e : set) {
//判断是否符合 "fun(arg0,arg1...)": { "callback": true } 格式
String key = e == null ? null : e.getKey();
JSONObject val = key != null && e.getValue() instanceof JSONObject ? ((JSONObject) e.getValue()) : null;
int index = val == null || key.endsWith(")") == false ? -1 : key.indexOf("(");
if (index > 0 && StringUtil.isName(key.substring(0, index))) {
boolean isCb = val.getBooleanValue(KEY_CALLBACK);
if (isCb) {
hasGlobalCallback = true;
}
if (globalInterfaceProxy == null) {
globalInterfaceProxy = new InterfaceProxy();
}
final JSONObject finalReq = req;
final InterfaceProxy globalProxy = globalInterfaceProxy;
globalInterfaceProxy.$_putCallback(key, new Listener<Object>() {
@Override
public void complete(Object data, Method method, InterfaceProxy proxy, Object... extras) throws Exception {
Log.d(TAG, "invokeMethod LISTENER_QUEUE.poll " + method);
if (isCb && listener != null) {
// JSONObject result = new JSONObject();
// result.put(method == null ? null : method.toString(), data);
// listener.complete(result, method, proxy, extras);
finalReq.putAll(globalProxy);
listener.complete(finalReq, method, proxy, extras);
}
}
});
}
}
// }
if (globalInterfaceProxy != null && GLOBAL_CALLBACK_MAP.containsValue(globalInterfaceProxy) == false) {
GLOBAL_CALLBACK_MAP.put(clazz, globalInterfaceProxy);
}
invokeMethod(clazz, instance, pkgName, clsName, methodName, methodArgs, listener, hasGlobalCallback ? globalInterfaceProxy : null, trace);
// 后端服务只允许在当前线程执行,只有客户端才允许设置在 UI 线程(主线程) 执行
// if (threadStr == null || THREAD_CURRENT_STRING.equals(threadStr) || THREAD_MAIN_STRING.equals(threadStr)) {
// invokeMethod(clazz, instance, pkgName, clsName, methodName, methodArgs, listener);
// }
// else if (THREAD_POOL_STRING.equals(threadStr)) { // || THREAD_NEW_STRING.equals(threadStr)) {
// final Object instance_ = instance;
// Runnable command = new Runnable() {
//
// @Override
// public void run() {
// try {
// invokeMethod(clazz, instance_, pkgName, clsName, methodName, methodArgs, listener);
// }
// catch (Throwable e) {
// completeWithError(pkgName, clsName, methodName, startTime, e, listener);
// }
// }
// };
//// if (THREAD_POOL_STRING.equals(threadStr)) {
// EXECUTOR_SERVICE.execute(command);
//// }
//// else {
//// new Thread(command).start();
//// }
// }
// else {
// throw new IllegalArgumentException("参数 " + KEY_THREAD + " 的值错误!只能是 [null, " + THREAD_CURRENT_STRING
// + ", " + THREAD_POOL_STRING + ", " + THREAD_MAIN_STRING + "] 中的一个!");
// }
}
catch (Throwable e) {
completeWithError(pkgName, clsName, methodName, startTime, e, listener, trace);
}
}
public static void invokeMethod(Class<?> clazz, final Object instance, String pkgName, String clsName
, String methodName, List<Argument> methodArgs, Listener<JSONObject> listener, InterfaceProxy globalInterfaceProxy, Boolean trace) throws Exception {
long startTime = System.currentTimeMillis();
try {
getInvokeResult(clazz, instance, methodName, methodArgs, new Listener<JSONObject>() {
@Override
public void complete(JSONObject data, Method method, InterfaceProxy proxy, Object... extras) throws Exception {
JSONObject result = JSON_CALLBACK.newSuccessResult();
if (data != null) {
result.putAll(data);
}
if (instance != null) {
result.put(KEY_THIS, parseJSON(instance.getClass(), instance)); //TODO InterfaceProxy proxy 改成泛型 I instance ?
}
if (trace != null && trace) {
Thread thread = Thread.currentThread();
result.put(KEY_TRACE, thread.getStackTrace());
}
if (listener != null) {
listener.complete(result);
}
}
}, globalInterfaceProxy);
}
catch (Throwable e) {
completeWithError(pkgName, clsName, methodName, startTime, e, listener, trace);
}
}
private static void completeWithError(String pkgName, String clsName, String methodName, long startTime, Throwable e, Listener<JSONObject> listener, Boolean trace) {
long endTime = System.currentTimeMillis();
e.printStackTrace();
if (e instanceof NoSuchMethodException) {
e = new IllegalArgumentException("字符 " + methodName + " 对应的方法不在 " + pkgName + "." + clsName + " 内!"
+ "\n请检查函数名和参数数量是否与已定义的函数一致!\n" + e.getMessage());
}
if (e instanceof InvocationTargetException) {
Throwable te = ((InvocationTargetException) e).getTargetException();
if (isEmpty(te.getMessage(), true) == false) { //到处把函数声明throws Exception改成throws Throwable挺麻烦
e = te instanceof Exception ? (Exception) te : new Exception(te.getMessage());
}
e = new IllegalArgumentException("字符 " + methodName + " 对应的方法传参类型错误!"
+ "\n请检查 key:value 中value的类型是否满足已定义的函数的要求!\n" + e.getMessage());
}
long duration = endTime - startTime;
String throwName = e.getClass().getTypeName();
Log.d(TAG, "getInvokeResult " + pkgName + "." + clsName + "." + methodName + " throw " + throwName + "! endTime = " + endTime + "; duration = " + duration + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\n");
JSONObject result = JSON_CALLBACK.newErrorResult(e);
result.put(KEY_TIME_DETAIL, startTime + "|" + duration + "|" + endTime);
result.put("throw", throwName);
result.put("cause", e.getCause());
if (trace == null || trace) {
result.put(KEY_TRACE, e.getStackTrace());
}
if (listener != null) {
try {
listener.complete(result);
}
catch (Exception e1) {
e1.printStackTrace();
}
}
}
public static List<Argument> getArgList(JSONObject req, String arrKey) {
JSONArray arr = req == null ? null : JSON.parseArray(req.getString(arrKey));
List<Argument> list = null;
if (arr != null) {
list = new ArrayList<>();
for (Object item : arr) {
if (item instanceof Boolean || item instanceof Number || item instanceof Collection
|| (item instanceof Map && ((Map<?, ?>) item).containsKey(KEY_VALUE) == false
&& ((Map<?, ?>) item).get(KEY_TYPE) instanceof String == false)
) {
list.add(new Argument(null, item));
}
else if (item instanceof String) {
String str = (String) item;
int index = str.indexOf(":");
String type = index < 0 ? null : str.substring(0, index);
String value = index < 0 ? str : str.substring(index + 1);
list.add(new Argument(type, value));
}
else { //null 合法,也要加,按顺序调用的
list.add(item == null ? null : JSON.parseObject(JSON.toJSONString(item), Argument.class));
}
}
}
return list;
}
/**获取类
* @param pkgName 包名
* @param clsName 类名
* @return
* @throws Exception
*/
public static Class<?> getInvokeClass(String pkgName, String clsName) throws Exception {
return CLASS_LOADER_CALLBACK.loadClass(pkgName, clsName, false);
}
/**获取实例
* @param clazz
* @param classArgs
* @param reuse
* @return
* @throws Exception
*/
public static Object getInvokeInstance(@NotNull Class<?> clazz, List<Argument> classArgs, Boolean reuse) throws Exception {
Objects.requireNonNull(clazz);
//new 出实例
Map<Object, Object> clsMap = INSTANCE_MAP.get(clazz);
if (clsMap == null) {
clsMap = new HashMap<>();
INSTANCE_MAP.put(clazz, clsMap);
}
String key = classArgs == null || classArgs.isEmpty() ? "" : JSON.toJSONString(classArgs);
Object instance = reuse != null && reuse ? clsMap.get(key) : null; //必须精确对应值,否则去除缓存的和需要的很可能不符
if (instance == null) {
if (classArgs == null || classArgs.isEmpty()) {
if (clazz.isAnnotation()) {
return clazz;
}
instance = clazz.isEnum() ? getEnumInstance(clazz, null) : clazz.newInstance();
}
else if (clazz.isEnum()) { //通过构造方法
Argument arg = classArgs.get(0);
String t = arg == null ? null : arg.getType();
Object v = arg == null ? null : arg.getValue();
if (classArgs.size() != 1
|| (v != null && v instanceof CharSequence != true)
|| (t != null && CharSequence.class.isAssignableFrom(getType(t, v, true)) == false)
) {
throw new IllegalArgumentException("enum " + clazz.getName() + " 对应的 classArgs 数量只能是 0 或 1 !且选项类型必须为 String!");
}
return getEnumInstance(clazz, v == null ? null : v.toString());
}
else { //通过构造方法
if (clazz.isAnnotation()) {
throw new IllegalArgumentException("@interface " + clazz.getName() + " 没有构造参数,对应的 classArgs 数量只能是 0!");
}
boolean exactConstructor = false; //指定某个构造方法,只要某一项 type 不为空就是
for (int i = 0; i < classArgs.size(); i++) {
Argument obj = classArgs.get(i);
if (obj != null && isEmpty(obj.getType(), true) == false) {
exactConstructor = true;
break;
}
}
Class<?>[] classArgTypes = new Class<?>[classArgs.size()];
Object[] classArgValues = new Object[classArgs.size()];
initTypesAndValues(classArgs, classArgTypes, classArgValues, exactConstructor);
if (exactConstructor) { //指定某个构造方法
Constructor<?> constructor = clazz.getConstructor(classArgTypes);
instance = constructor.newInstance(classArgValues);
}
else { //尝试参数数量一致的构造方法
Constructor<?>[] constructors = clazz.getConstructors();
if (constructors != null) {
for (int i = 0; i < constructors.length; i++) {
if (constructors[i] != null && constructors[i].getParameterCount() == classArgValues.length) {
try {
constructors[i].setAccessible(true);
}
catch (Throwable e) {
e.printStackTrace();
}
try {
instance = constructors[i].newInstance(classArgValues);
break;
}
catch (Throwable e) {
e.printStackTrace();
}
}
}
}
}
}
if (instance == null) { //通过默认方法
throw new NullPointerException("找不到 " + clazz.getName() + " 以及 classArgs 对应的构造方法!");
}
clsMap.put(key, instance);
}
return instance;
}
@SuppressWarnings("rawtypes")
public static Object getEnumInstance(Enum em, String name) throws NoSuchFieldException {
return getEnumInstance(em == null ? null : em.getDeclaringClass(), name);
}
@SuppressWarnings("rawtypes")
public static Object getEnumInstance(Class clazz, String name) throws NoSuchFieldException {
Object[] constants = clazz == null ? null : clazz.getEnumConstants();
if (constants == null || constants.length < 0) {
return null;
}
if (StringUtil.isEmpty(name, false)) {
return constants[0];
}
for (int i = 0; i < constants.length; i++) {
if (name.equals(constants[i].toString())) {
return constants[i];
}
}
throw new NoSuchFieldException("enum " + clazz.getName() + " 不存在 " + name + " 这个值!");
}
@SuppressWarnings("rawtypes")
public static LinkedHashMap<Integer, String> mapEnumConstants(Enum em) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
return mapEnumConstants(em.getDeclaringClass());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static LinkedHashMap<Integer, String> mapEnumConstants(Class clazz) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
Method toName = clazz.getMethod("toName");
Method toCode = clazz.getMethod("toCode");
Object[] objs = clazz.getEnumConstants();
for (Object obj : objs) {
map.put((Integer) toCode.invoke(obj), (String) toName.invoke(obj));
}
return map;
}
/**获取方法
* @param clazz
* @param methodName
* @param methodArgs
* @return
* @throws Exception
*/
public static Method getInvokeMethod(@NotNull Class<?> clazz, @NotNull String methodName, List<Argument> methodArgs) throws Exception {
Objects.requireNonNull(clazz);
Objects.requireNonNull(methodName);
//method argument, types and values
Class<?>[] types = null;
Object[] args = null;
if (methodArgs != null && methodArgs.isEmpty() == false) {
types = new Class<?>[methodArgs.size()];
args = new Object[methodArgs.size()];
initTypesAndValues(methodArgs, types, args, true);
}
return clazz.getMethod(methodName, types);
}
/**执行方法并返回结果
* @param instance
* @param methodName
* @param methodArgs
* @param listener 如果确定是同步的,则传 null
* @return 同步可能 return null,异步一定 return null
* @throws Exception
*/
public static Object getInvokeResult(@NotNull Class<?> clazz, Object instance, @NotNull String methodName
, List<Argument> methodArgs, Listener<JSONObject> listener, InterfaceProxy globalInterfaceProxy) throws Exception {
Objects.requireNonNull(clazz);
Objects.requireNonNull(methodName);
final int size = methodArgs == null ? 0 : methodArgs.size();
final boolean isEmpty = size <= 0;
//method argument, types and values
Class<?>[] types = isEmpty ? null : new Class<?>[size];
Object[] args = isEmpty ? null : new Object[size];
if (isEmpty == false) {
initTypesAndValues(methodArgs, types, args, true, false);
}
Method method = null;
try {
method = clazz.getMethod(methodName, types);
} catch (Throwable e) {
method = clazz.getDeclaredMethod(methodName, types);
if (method != null) { // JDK 9+ && method.trySetAccessible() == false) {
method.setAccessible(true);
}
}
final Method finalMethod = method;
final long[] startTime = new long[]{ System.currentTimeMillis() }; // 必须在 itemListener 前初始化,但又得在后面重新赋值以获得最准确的时间