forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProxyGenerator.java
1905 lines (1661 loc) · 78.8 KB
/
ProxyGenerator.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 (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.reflect;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import sun.security.action.GetBooleanAction;
/**
* ProxyGenerator contains the code to generate a dynamic proxy class
* for the java.lang.reflect.Proxy API.
*
* The external interfaces to ProxyGenerator is the static
* "generateProxyClass" method.
*
* @author Peter Jones
* @since 1.3
*/
// 代理类字节码生成器
class ProxyGenerator {
/*
* In the comments below, "JVMS" refers to The Java Virtual Machine
* Specification Second Edition and "JLS" refers to the original
* version of The Java Language Specification, unless otherwise
* specified.
*/
/* generate 1.5-era class file version */
private static final int CLASSFILE_MAJOR_VERSION = 49;
private static final int CLASSFILE_MINOR_VERSION = 0;
/*
* beginning of constants copied from
* sun.tools.java.RuntimeConstants (which no longer exists):
*/
/* constant pool tags */
private static final int CONSTANT_UTF8 = 1;
private static final int CONSTANT_UNICODE = 2;
private static final int CONSTANT_INTEGER = 3;
private static final int CONSTANT_FLOAT = 4;
private static final int CONSTANT_LONG = 5;
private static final int CONSTANT_DOUBLE = 6;
private static final int CONSTANT_CLASS = 7;
private static final int CONSTANT_STRING = 8;
private static final int CONSTANT_FIELD = 9;
private static final int CONSTANT_METHOD = 10;
private static final int CONSTANT_INTERFACEMETHOD = 11;
private static final int CONSTANT_NAMEANDTYPE = 12;
/* access and modifier flags */
private static final int ACC_PUBLIC = 0x00000001;
private static final int ACC_PRIVATE = 0x00000002;
// private static final int ACC_PROTECTED = 0x00000004;
private static final int ACC_STATIC = 0x00000008;
private static final int ACC_FINAL = 0x00000010;
// private static final int ACC_SYNCHRONIZED = 0x00000020;
// private static final int ACC_VOLATILE = 0x00000040;
// private static final int ACC_TRANSIENT = 0x00000080;
// private static final int ACC_NATIVE = 0x00000100;
// private static final int ACC_INTERFACE = 0x00000200;
// private static final int ACC_ABSTRACT = 0x00000400;
private static final int ACC_SUPER = 0x00000020;
// private static final int ACC_STRICT = 0x00000800;
/* opcodes */
// private static final int opc_nop = 0;
private static final int opc_aconst_null = 1;
// private static final int opc_iconst_m1 = 2;
private static final int opc_iconst_0 = 3;
// private static final int opc_iconst_1 = 4;
// private static final int opc_iconst_2 = 5;
// private static final int opc_iconst_3 = 6;
// private static final int opc_iconst_4 = 7;
// private static final int opc_iconst_5 = 8;
// private static final int opc_lconst_0 = 9;
// private static final int opc_lconst_1 = 10;
// private static final int opc_fconst_0 = 11;
// private static final int opc_fconst_1 = 12;
// private static final int opc_fconst_2 = 13;
// private static final int opc_dconst_0 = 14;
// private static final int opc_dconst_1 = 15;
private static final int opc_bipush = 16;
private static final int opc_sipush = 17;
private static final int opc_ldc = 18;
private static final int opc_ldc_w = 19;
// private static final int opc_ldc2_w = 20;
private static final int opc_iload = 21;
private static final int opc_lload = 22;
private static final int opc_fload = 23;
private static final int opc_dload = 24;
private static final int opc_aload = 25;
private static final int opc_iload_0 = 26;
// private static final int opc_iload_1 = 27;
// private static final int opc_iload_2 = 28;
// private static final int opc_iload_3 = 29;
private static final int opc_lload_0 = 30;
// private static final int opc_lload_1 = 31;
// private static final int opc_lload_2 = 32;
// private static final int opc_lload_3 = 33;
private static final int opc_fload_0 = 34;
// private static final int opc_fload_1 = 35;
// private static final int opc_fload_2 = 36;
// private static final int opc_fload_3 = 37;
private static final int opc_dload_0 = 38;
// private static final int opc_dload_1 = 39;
// private static final int opc_dload_2 = 40;
// private static final int opc_dload_3 = 41;
private static final int opc_aload_0 = 42;
// private static final int opc_aload_1 = 43;
// private static final int opc_aload_2 = 44;
// private static final int opc_aload_3 = 45;
// private static final int opc_iaload = 46;
// private static final int opc_laload = 47;
// private static final int opc_faload = 48;
// private static final int opc_daload = 49;
// private static final int opc_aaload = 50;
// private static final int opc_baload = 51;
// private static final int opc_caload = 52;
// private static final int opc_saload = 53;
// private static final int opc_istore = 54;
// private static final int opc_lstore = 55;
// private static final int opc_fstore = 56;
// private static final int opc_dstore = 57;
private static final int opc_astore = 58;
// private static final int opc_istore_0 = 59;
// private static final int opc_istore_1 = 60;
// private static final int opc_istore_2 = 61;
// private static final int opc_istore_3 = 62;
// private static final int opc_lstore_0 = 63;
// private static final int opc_lstore_1 = 64;
// private static final int opc_lstore_2 = 65;
// private static final int opc_lstore_3 = 66;
// private static final int opc_fstore_0 = 67;
// private static final int opc_fstore_1 = 68;
// private static final int opc_fstore_2 = 69;
// private static final int opc_fstore_3 = 70;
// private static final int opc_dstore_0 = 71;
// private static final int opc_dstore_1 = 72;
// private static final int opc_dstore_2 = 73;
// private static final int opc_dstore_3 = 74;
private static final int opc_astore_0 = 75;
// private static final int opc_astore_1 = 76;
// private static final int opc_astore_2 = 77;
// private static final int opc_astore_3 = 78;
// private static final int opc_iastore = 79;
// private static final int opc_lastore = 80;
// private static final int opc_fastore = 81;
// private static final int opc_dastore = 82;
private static final int opc_aastore = 83;
// private static final int opc_bastore = 84;
// private static final int opc_castore = 85;
// private static final int opc_sastore = 86;
private static final int opc_pop = 87;
// private static final int opc_pop2 = 88;
private static final int opc_dup = 89;
// private static final int opc_dup_x1 = 90;
// private static final int opc_dup_x2 = 91;
// private static final int opc_dup2 = 92;
// private static final int opc_dup2_x1 = 93;
// private static final int opc_dup2_x2 = 94;
// private static final int opc_swap = 95;
// private static final int opc_iadd = 96;
// private static final int opc_ladd = 97;
// private static final int opc_fadd = 98;
// private static final int opc_dadd = 99;
// private static final int opc_isub = 100;
// private static final int opc_lsub = 101;
// private static final int opc_fsub = 102;
// private static final int opc_dsub = 103;
// private static final int opc_imul = 104;
// private static final int opc_lmul = 105;
// private static final int opc_fmul = 106;
// private static final int opc_dmul = 107;
// private static final int opc_idiv = 108;
// private static final int opc_ldiv = 109;
// private static final int opc_fdiv = 110;
// private static final int opc_ddiv = 111;
// private static final int opc_irem = 112;
// private static final int opc_lrem = 113;
// private static final int opc_frem = 114;
// private static final int opc_drem = 115;
// private static final int opc_ineg = 116;
// private static final int opc_lneg = 117;
// private static final int opc_fneg = 118;
// private static final int opc_dneg = 119;
// private static final int opc_ishl = 120;
// private static final int opc_lshl = 121;
// private static final int opc_ishr = 122;
// private static final int opc_lshr = 123;
// private static final int opc_iushr = 124;
// private static final int opc_lushr = 125;
// private static final int opc_iand = 126;
// private static final int opc_land = 127;
// private static final int opc_ior = 128;
// private static final int opc_lor = 129;
// private static final int opc_ixor = 130;
// private static final int opc_lxor = 131;
// private static final int opc_iinc = 132;
// private static final int opc_i2l = 133;
// private static final int opc_i2f = 134;
// private static final int opc_i2d = 135;
// private static final int opc_l2i = 136;
// private static final int opc_l2f = 137;
// private static final int opc_l2d = 138;
// private static final int opc_f2i = 139;
// private static final int opc_f2l = 140;
// private static final int opc_f2d = 141;
// private static final int opc_d2i = 142;
// private static final int opc_d2l = 143;
// private static final int opc_d2f = 144;
// private static final int opc_i2b = 145;
// private static final int opc_i2c = 146;
// private static final int opc_i2s = 147;
// private static final int opc_lcmp = 148;
// private static final int opc_fcmpl = 149;
// private static final int opc_fcmpg = 150;
// private static final int opc_dcmpl = 151;
// private static final int opc_dcmpg = 152;
// private static final int opc_ifeq = 153;
// private static final int opc_ifne = 154;
// private static final int opc_iflt = 155;
// private static final int opc_ifge = 156;
// private static final int opc_ifgt = 157;
// private static final int opc_ifle = 158;
// private static final int opc_if_icmpeq = 159;
// private static final int opc_if_icmpne = 160;
// private static final int opc_if_icmplt = 161;
// private static final int opc_if_icmpge = 162;
// private static final int opc_if_icmpgt = 163;
// private static final int opc_if_icmple = 164;
// private static final int opc_if_acmpeq = 165;
// private static final int opc_if_acmpne = 166;
// private static final int opc_goto = 167;
// private static final int opc_jsr = 168;
// private static final int opc_ret = 169;
// private static final int opc_tableswitch = 170;
// private static final int opc_lookupswitch = 171;
private static final int opc_ireturn = 172;
private static final int opc_lreturn = 173;
private static final int opc_freturn = 174;
private static final int opc_dreturn = 175;
private static final int opc_areturn = 176;
private static final int opc_return = 177;
private static final int opc_getstatic = 178;
private static final int opc_putstatic = 179;
private static final int opc_getfield = 180;
// private static final int opc_putfield = 181;
private static final int opc_invokevirtual = 182;
private static final int opc_invokespecial = 183;
private static final int opc_invokestatic = 184;
private static final int opc_invokeinterface = 185;
private static final int opc_new = 187;
// private static final int opc_newarray = 188;
private static final int opc_anewarray = 189;
// private static final int opc_arraylength = 190;
private static final int opc_athrow = 191;
private static final int opc_checkcast = 192;
// private static final int opc_instanceof = 193;
// private static final int opc_monitorenter = 194;
// private static final int opc_monitorexit = 195;
private static final int opc_wide = 196;
// private static final int opc_multianewarray = 197;
// private static final int opc_ifnull = 198;
// private static final int opc_ifnonnull = 199;
// private static final int opc_goto_w = 200;
// private static final int opc_jsr_w = 201;
// end of constants copied from sun.tools.java.RuntimeConstants
/** name of the superclass of proxy classes */
private static final String superclassName = "java/lang/reflect/Proxy";
/** name of field for storing a proxy instance's invocation handler */
private static final String handlerFieldName = "h";
/** debugging flag for saving generated class files */
// 控制是否将生成的代理类保存到根目录
private static final boolean saveGeneratedFiles = AccessController.doPrivileged(new GetBooleanAction("jdk.proxy.ProxyGenerator.saveGeneratedFiles"));
/** name of proxy class */
private String className; // 代理类类名
/** proxy interfaces */
private Class<?>[] interfaces; // 代理类接口
/** proxy class access flags */
private int accessFlags; // 代理类访问修饰符
/** constant pool of class being generated */
private ConstantPool cp = new ConstantPool(); // 代理类的构造方法池
/** FieldInfo struct for each field of generated class */
private List<FieldInfo> fields = new ArrayList<>(); // 字段列表
/** MethodInfo struct for each method of generated class */
private List<MethodInfo> methods = new ArrayList<>(); // 方法列表(包括构造器和初始化块)
/**
* maps method signature string to list of ProxyMethod objects for
* proxy methods with that signature
*/
// <方法签名,方法>键值对,不包括构造器和初始化块
private Map<String, List<ProxyMethod>> proxyMethods = new HashMap<>();
/** count of ProxyMethod objects added to proxyMethods */
private int proxyMethodCount = 0; // proxyMethods中代理方法数量
/** preloaded Method objects for methods in java.lang.Object */
private static Method hashCodeMethod; // Object#hashCode
private static Method equalsMethod; // Object#equals
private static Method toStringMethod; // Object#toString
// 获取Object类中的hashCode/equals/toString方法
static {
try {
hashCodeMethod = Object.class.getMethod("hashCode");
equalsMethod = Object.class.getMethod("equals", new Class<?>[]{Object.class});
toStringMethod = Object.class.getMethod("toString");
} catch(NoSuchMethodException e) {
throw new NoSuchMethodError(e.getMessage());
}
}
/**
* Construct a ProxyGenerator to generate a proxy class with the
* specified name and for the given interfaces.
*
* A ProxyGenerator object contains the state for the ongoing
* generation of a particular proxy class.
*/
private ProxyGenerator(String className, Class<?>[] interfaces, int accessFlags) {
this.className = className;
this.interfaces = interfaces;
this.accessFlags = accessFlags;
}
/**
* Generate a public proxy class given a name and a list of proxy interfaces.
*/
// 生成代理类字节码
static byte[] generateProxyClass(final String name, Class<?>[] interfaces) {
return generateProxyClass(name, interfaces, (ACC_PUBLIC | ACC_FINAL | ACC_SUPER));
}
/**
* Generate a proxy class given a name and a list of proxy interfaces.
*
* @param name the class name of the proxy class
* @param interfaces proxy interfaces
* @param accessFlags access flags of the proxy class
*/
// 生成代理类字节码
static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) {
ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
// 生成代理类的字节码
final byte[] classFile = gen.generateClassFile();
// 如果不需要保存代理文件,则直接返回字节码就可以了
if(!saveGeneratedFiles) {
return classFile;
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try {
int i = name.lastIndexOf('.');
Path path;
// 存在包名
if(i>0) {
// 将包名转换为路径
Path dir = Path.of(name.substring(0, i).replace('.', File.separatorChar));
// 创建目录
Files.createDirectories(dir);
// 解析字节码存放路径
path = dir.resolve(name.substring(i + 1, name.length()) + ".class");
} else {
path = Path.of(name + ".class");
}
// 将字节码文件写入指定的路径
Files.write(path, classFile);
return null;
} catch(IOException e) {
throw new InternalError("I/O exception saving generated file: " + e);
}
}
});
return classFile;
}
/**
* Generate a class file for the proxy class.
* This method drives the class file generation process.
*/
// 生成代理类的字节码
private byte[] generateClassFile() {
/* ============================================================
* Step 1: Assemble ProxyMethod objects for all methods to generate proxy dispatching code for.
* ============================================================
*/
/*
* Record that proxy methods are needed for the hashCode, equals, and toString methods of java.lang.Object.
* This is done before the methods from the proxy interfaces
* so that the methods from java.lang.Object take precedence over duplicate methods in the proxy interfaces.
*/
addProxyMethod(hashCodeMethod, Object.class);
addProxyMethod(equalsMethod, Object.class);
addProxyMethod(toStringMethod, Object.class);
/*
* Now record all of the methods from the proxy interfaces, giving
* earlier interfaces precedence over later ones with duplicate
* methods.
*/
// 遍历代理接口,将接口方法添加到代理类中
for (Class<?> intf : interfaces) {
for (Method m : intf.getMethods()) {
if (!Modifier.isStatic(m.getModifiers())) {
addProxyMethod(m, intf);
}
}
}
/*
* For each set of proxy methods with the same signature,
* verify that the methods' return types are compatible.
*/
// 对于相同签名的方法,验证返回类型是否兼容
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
checkReturnTypes(sigmethods);
}
/* ============================================================
* Step 2: Assemble FieldInfo and MethodInfo structs for all of fields and methods in the class we are generating.
* ============================================================
*/
try {
methods.add(generateConstructor());
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// add static field for method's Method object
fields.add(new FieldInfo(pm.methodFieldName, "Ljava/lang/reflect/Method;", ACC_PRIVATE | ACC_STATIC));
// generate code for proxy method and add it
methods.add(pm.generateMethod());
}
}
methods.add(generateStaticInitializer());
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception", e);
}
if (methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
}
if (fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
}
/* ============================================================
* Step 3: Write the final class file.
* ============================================================
*/
/*
* Make sure that constant pool indexes are reserved for the following items before starting to write the final class file.
*/
cp.getClass(dotToSlash(className));
cp.getClass(superclassName);
for (Class<?> intf: interfaces) {
cp.getClass(dotToSlash(intf.getName()));
}
/*
* Disallow new constant pool additions beyond this point, since we are about to write the final constant pool table.
*/
cp.setReadOnly();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
/*
* Write all the items of the "ClassFile" structure.
* See JVMS section 4.1.
*/
// u4 magic;
dout.writeInt(0xCAFEBABE);
// u2 minor_version;
dout.writeShort(CLASSFILE_MINOR_VERSION);
// u2 major_version;
dout.writeShort(CLASSFILE_MAJOR_VERSION);
cp.write(dout); // (write constant pool)
// u2 access_flags;
dout.writeShort(accessFlags);
// u2 this_class;
dout.writeShort(cp.getClass(dotToSlash(className)));
// u2 super_class;
dout.writeShort(cp.getClass(superclassName));
// u2 interfaces_count;
dout.writeShort(interfaces.length);
// u2 interfaces[interfaces_count];
for (Class<?> intf : interfaces) {
dout.writeShort(cp.getClass(dotToSlash(intf.getName())));
}
// u2 fields_count;
dout.writeShort(fields.size());
// field_info fields[fields_count];
for (FieldInfo f : fields) {
f.write(dout);
}
// u2 methods_count;
dout.writeShort(methods.size());
// method_info methods[methods_count];
for (MethodInfo m : methods) {
m.write(dout);
}
// u2 attributes_count;
dout.writeShort(0); // (no ClassFile attributes for proxy classes)
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception", e);
}
return bout.toByteArray();
}
/**
* Add another method to be proxied, either by creating a new
* ProxyMethod object or augmenting an old one for a duplicate
* method.
*
* "fromClass" indicates the proxy interface that the method was
* found through, which may be different from (a subinterface of)
* the method's "declaring class". Note that the first Method
* object passed for a given name and descriptor identifies the
* Method object (and thus the declaring class) that will be
* passed to the invocation handler's "invoke" method for a given
* set of duplicate methods.
*/
// 为代理类添加fromClass类中的m方法
private void addProxyMethod(Method m, Class<?> fromClass) {
String name = m.getName(); // 方法名称
Class<?>[] parameterTypes = m.getParameterTypes(); // 形参类型
Class<?> returnType = m.getReturnType(); // 返回类型
Class<?>[] exceptionTypes = m.getExceptionTypes(); // 异常类型
String sig = name + getParameterDescriptors(parameterTypes);
List<ProxyMethod> sigmethods = proxyMethods.get(sig);
// 如果出现相同签名的方法,进一步判断返回类型,对返回类型一样的方法使其异常类型兼容
if(sigmethods != null) {
for(ProxyMethod pm : sigmethods) {
if(returnType == pm.returnType) {
/*
* Found a match: reduce exception types to the
* greatest set of exceptions that can thrown
* compatibly with the throws clauses of both
* overridden methods.
*/
List<Class<?>> legalExceptions = new ArrayList<>();
collectCompatibleTypes(exceptionTypes, pm.exceptionTypes, legalExceptions);
collectCompatibleTypes(pm.exceptionTypes, exceptionTypes, legalExceptions);
pm.exceptionTypes = new Class<?>[legalExceptions.size()];
pm.exceptionTypes = legalExceptions.toArray(pm.exceptionTypes);
return;
}
}
} else {
sigmethods = new ArrayList<>(3);
proxyMethods.put(sig, sigmethods);
}
// 缓存相同签名的方法
sigmethods.add(new ProxyMethod(name, parameterTypes, returnType, exceptionTypes, fromClass));
}
/**
* For a given set of proxy methods with the same signature, check
* that their return types are compatible according to the Proxy
* specification.
*
* Specifically, if there is more than one such method, then all
* of the return types must be reference types, and there must be
* one return type that is assignable to each of the rest of them.
*/
// 检查返回类型是否兼容
private static void checkReturnTypes(List<ProxyMethod> methods) {
/*
* If there is only one method with a given signature, there
* cannot be a conflict. This is the only case in which a
* primitive (or void) return type is allowed.
*/
if (methods.size() < 2) {
return;
}
/*
* List of return types that are not yet known to be
* assignable from ("covered" by) any of the others.
*/
LinkedList<Class<?>> uncoveredReturnTypes = new LinkedList<>();
nextNewReturnType:
for (ProxyMethod pm : methods) {
Class<?> newReturnType = pm.returnType;
if (newReturnType.isPrimitive()) {
throw new IllegalArgumentException(
"methods with same signature " +
getFriendlyMethodSignature(pm.methodName,
pm.parameterTypes) +
" but incompatible return types: " +
newReturnType.getName() + " and others");
}
boolean added = false;
/*
* Compare the new return type to the existing uncovered
* return types.
*/
ListIterator<Class<?>> liter = uncoveredReturnTypes.listIterator();
while (liter.hasNext()) {
Class<?> uncoveredReturnType = liter.next();
/*
* If an existing uncovered return type is assignable
* to this new one, then we can forget the new one.
*/
if (newReturnType.isAssignableFrom(uncoveredReturnType)) {
assert !added;
continue nextNewReturnType;
}
/*
* If the new return type is assignable to an existing
* uncovered one, then should replace the existing one
* with the new one (or just forget the existing one,
* if the new one has already be put in the list).
*/
if (uncoveredReturnType.isAssignableFrom(newReturnType)) {
// (we can assume that each return type is unique)
if (!added) {
liter.set(newReturnType);
added = true;
} else {
liter.remove();
}
}
}
/*
* If we got through the list of existing uncovered return
* types without an assignability relationship, then add
* the new return type to the list of uncovered ones.
*/
if (!added) {
uncoveredReturnTypes.add(newReturnType);
}
}
/*
* We shouldn't end up with more than one return type that is
* not assignable from any of the others.
*/
if (uncoveredReturnTypes.size() > 1) {
ProxyMethod pm = methods.get(0);
throw new IllegalArgumentException("methods with same signature " + getFriendlyMethodSignature(pm.methodName, pm.parameterTypes) + " but incompatible return types: " + uncoveredReturnTypes);
}
}
/**
* A FieldInfo object contains information about a particular field
* in the class being generated. The class mirrors the data items of
* the "field_info" structure of the class file format (see JVMS 4.5).
*/
// 字段信息
private class FieldInfo {
public int accessFlags;
public String name;
public String descriptor;
public FieldInfo(String name, String descriptor, int accessFlags) {
this.name = name;
this.descriptor = descriptor;
this.accessFlags = accessFlags;
/*
* Make sure that constant pool indexes are reserved for the
* following items before starting to write the final class file.
*/
cp.getUtf8(name);
cp.getUtf8(descriptor);
}
public void write(DataOutputStream out) throws IOException {
/*
* Write all the items of the "field_info" structure.
* See JVMS section 4.5.
*/
// u2 access_flags;
out.writeShort(accessFlags);
// u2 name_index;
out.writeShort(cp.getUtf8(name));
// u2 descriptor_index;
out.writeShort(cp.getUtf8(descriptor));
// u2 attributes_count;
out.writeShort(0); // (no field_info attributes for proxy classes)
}
}
/**
* A MethodInfo object contains information about a particular method
* in the class being generated. This class mirrors the data items of
* the "method_info" structure of the class file format (see JVMS 4.6).
*/
// 方法信息
private class MethodInfo {
public int accessFlags;
public String name;
public String descriptor;
public short maxStack;
public short maxLocals;
public ByteArrayOutputStream code = new ByteArrayOutputStream();
public List<ExceptionTableEntry> exceptionTable = new ArrayList<ExceptionTableEntry>();
public short[] declaredExceptions;
public MethodInfo(String name, String descriptor, int accessFlags) {
this.name = name;
this.descriptor = descriptor;
this.accessFlags = accessFlags;
/*
* Make sure that constant pool indexes are reserved for the
* following items before starting to write the final class file.
*/
cp.getUtf8(name);
cp.getUtf8(descriptor);
cp.getUtf8("Code");
cp.getUtf8("Exceptions");
}
public void write(DataOutputStream out) throws IOException {
/*
* Write all the items of the "method_info" structure.
* See JVMS section 4.6.
*/
// u2 access_flags;
out.writeShort(accessFlags);
// u2 name_index;
out.writeShort(cp.getUtf8(name));
// u2 descriptor_index;
out.writeShort(cp.getUtf8(descriptor));
// u2 attributes_count;
out.writeShort(2); // (two method_info attributes:)
// Write "Code" attribute. See JVMS section 4.7.3.
// u2 attribute_name_index;
out.writeShort(cp.getUtf8("Code"));
// u4 attribute_length;
out.writeInt(12 + code.size() + 8 * exceptionTable.size());
// u2 max_stack;
out.writeShort(maxStack);
// u2 max_locals;
out.writeShort(maxLocals);
// u2 code_length;
out.writeInt(code.size());
// u1 code[code_length];
code.writeTo(out);
// u2 exception_table_length;
out.writeShort(exceptionTable.size());
for(ExceptionTableEntry e : exceptionTable) {
// u2 start_pc;
out.writeShort(e.startPc);
// u2 end_pc;
out.writeShort(e.endPc);
// u2 handler_pc;
out.writeShort(e.handlerPc);
// u2 catch_type;
out.writeShort(e.catchType);
}
// u2 attributes_count;
out.writeShort(0);
// write "Exceptions" attribute. See JVMS section 4.7.4.
// u2 attribute_name_index;
out.writeShort(cp.getUtf8("Exceptions"));
// u4 attributes_length;
out.writeInt(2 + 2 * declaredExceptions.length);
// u2 number_of_exceptions;
out.writeShort(declaredExceptions.length);
// u2 exception_index_table[number_of_exceptions];
for(short value : declaredExceptions) {
out.writeShort(value);
}
}
}
/**
* An ExceptionTableEntry object holds values for the data items of
* an entry in the "exception_table" item of the "Code" attribute of
* "method_info" structures (see JVMS 4.7.3).
*/
// 异常信息
private static class ExceptionTableEntry {
public short startPc;
public short endPc;
public short handlerPc;
public short catchType;
public ExceptionTableEntry(short startPc, short endPc, short handlerPc, short catchType) {
this.startPc = startPc;
this.endPc = endPc;
this.handlerPc = handlerPc;
this.catchType = catchType;
}
}
/**
* A ProxyMethod object represents a proxy method in the proxy class
* being generated: a method whose implementation will encode and
* dispatch invocations to the proxy instance's invocation handler.
*/
private class ProxyMethod {
public String methodName;
public Class<?>[] parameterTypes;
public Class<?> returnType;
public Class<?>[] exceptionTypes;
public Class<?> fromClass;
public String methodFieldName;
private ProxyMethod(String methodName, Class<?>[] parameterTypes, Class<?> returnType, Class<?>[] exceptionTypes, Class<?> fromClass) {
this.methodName = methodName;
this.parameterTypes = parameterTypes;
this.returnType = returnType;
this.exceptionTypes = exceptionTypes;
this.fromClass = fromClass;
this.methodFieldName = "m" + proxyMethodCount++;
}
/**
* Return a MethodInfo object for this method, including generating
* the code and exception table entry.
*/
private MethodInfo generateMethod() throws IOException {
String desc = getMethodDescriptor(parameterTypes, returnType);
MethodInfo minfo = new MethodInfo(methodName, desc, ACC_PUBLIC | ACC_FINAL);
int[] parameterSlot = new int[parameterTypes.length];
int nextSlot = 1;
for (int i = 0; i < parameterSlot.length; i++) {
parameterSlot[i] = nextSlot;
nextSlot += getWordsPerType(parameterTypes[i]);
}
int localSlot0 = nextSlot;
short pc, tryBegin = 0, tryEnd;
DataOutputStream out = new DataOutputStream(minfo.code);
code_aload(0, out);
out.writeByte(opc_getfield);
out.writeShort(cp.getFieldRef(superclassName, handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));
code_aload(0, out);
out.writeByte(opc_getstatic);
out.writeShort(cp.getFieldRef(dotToSlash(className), methodFieldName, "Ljava/lang/reflect/Method;"));
if (parameterTypes.length > 0) {
code_ipush(parameterTypes.length, out);
out.writeByte(opc_anewarray);
out.writeShort(cp.getClass("java/lang/Object"));
for (int i = 0; i < parameterTypes.length; i++) {
out.writeByte(opc_dup);
code_ipush(i, out);
codeWrapArgument(parameterTypes[i], parameterSlot[i], out);
out.writeByte(opc_aastore);
}
} else {
out.writeByte(opc_aconst_null);
}
out.writeByte(opc_invokeinterface);
out.writeShort(cp.getInterfaceMethodRef("java/lang/reflect/InvocationHandler", "invoke", "(Ljava/lang/Object;Ljava/lang/reflect/Method;" + "[Ljava/lang/Object;)Ljava/lang/Object;"));
out.writeByte(4);
out.writeByte(0);
if (returnType == void.class) {
out.writeByte(opc_pop);
out.writeByte(opc_return);
} else {
codeUnwrapReturnValue(returnType, out);
}
tryEnd = pc = (short) minfo.code.size();
List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
if (catchList.size() > 0) {
for (Class<?> ex : catchList) {
minfo.exceptionTable.add(new ExceptionTableEntry(tryBegin, tryEnd, pc, cp.getClass(dotToSlash(ex.getName()))));
}
out.writeByte(opc_athrow);
pc = (short) minfo.code.size();
minfo.exceptionTable.add(new ExceptionTableEntry(tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));
code_astore(localSlot0, out);
out.writeByte(opc_new);
out.writeShort(cp.getClass("java/lang/reflect/UndeclaredThrowableException"));
out.writeByte(opc_dup);
code_aload(localSlot0, out);
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef("java/lang/reflect/UndeclaredThrowableException", "<init>", "(Ljava/lang/Throwable;)V"));
out.writeByte(opc_athrow);
}
if (minfo.code.size() > 65535) {
throw new IllegalArgumentException("code size limit exceeded");
}
minfo.maxStack = 10;
minfo.maxLocals = (short) (localSlot0 + 1);
minfo.declaredExceptions = new short[exceptionTypes.length];
for (int i = 0; i < exceptionTypes.length; i++) {
minfo.declaredExceptions[i] = cp.getClass(dotToSlash(exceptionTypes[i].getName()));
}
return minfo;
}