forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Class.java
4319 lines (3893 loc) · 188 KB
/
Class.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) 1994, 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;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.module.ModuleReader;
import java.lang.ref.SoftReference;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
import jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.loader.BootLoader;
import jdk.internal.loader.BuiltinClassLoader;
import jdk.internal.misc.Unsafe;
import jdk.internal.module.Resources;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.ConstantPool;
import jdk.internal.reflect.Reflection;
import jdk.internal.reflect.ReflectionFactory;
import jdk.internal.vm.annotation.ForceInline;
import sun.reflect.annotation.AnnotationParser;
import sun.reflect.annotation.AnnotationSupport;
import sun.reflect.annotation.AnnotationType;
import sun.reflect.annotation.TypeAnnotationParser;
import sun.reflect.generics.factory.CoreReflectionFactory;
import sun.reflect.generics.factory.GenericsFactory;
import sun.reflect.generics.repository.ClassRepository;
import sun.reflect.generics.repository.ConstructorRepository;
import sun.reflect.generics.repository.MethodRepository;
import sun.reflect.generics.scope.ClassScope;
import sun.reflect.misc.ReflectUtil;
import sun.security.util.SecurityConstants;
/**
* Instances of the class {@code Class} represent classes and interfaces
* in a running Java application. An enum type is a kind of class and an
* annotation type is a kind of interface. Every array also
* belongs to a class that is reflected as a {@code Class} object
* that is shared by all arrays with the same element type and number
* of dimensions. The primitive Java types ({@code boolean},
* {@code byte}, {@code char}, {@code short},
* {@code int}, {@code long}, {@code float}, and
* {@code double}), and the keyword {@code void} are also
* represented as {@code Class} objects.
*
* <p> {@code Class} has no public constructor. Instead a {@code Class}
* object is constructed automatically by the Java Virtual Machine
* when a class loader invokes one of the
* {@link ClassLoader#defineClass(String, byte[], int, int) defineClass} methods
* and passes the bytes of a {@code class} file.
*
* <p> The methods of class {@code Class} expose many characteristics of a
* class or interface. Most characteristics are derived from the {@code class}
* file that the class loader passed to the Java Virtual Machine. A few
* characteristics are determined by the class loading environment at run time,
* such as the module returned by {@link #getModule() getModule()}.
*
* <p> Some methods of class {@code Class} expose whether the declaration of
* a class or interface in Java source code was <em>enclosed</em> within
* another declaration. Other methods describe how a class or interface
* is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of
* classes and interfaces, in the same run-time package, that
* allow mutual access to their {@code private} members.
* The classes and interfaces are known as <em>nestmates</em>.
* One nestmate acts as the
* <em>nest host</em>, and enumerates the other nestmates which
* belong to the nest; each of them in turn records it as the nest host.
* The classes and interfaces which belong to a nest, including its host, are
* determined when
* {@code class} files are generated, for example, a Java compiler
* will typically record a top-level class as the host of a nest where the
* other members are the classes and interfaces whose declarations are
* enclosed within the top-level class declaration.
*
* <p> The following example uses a {@code Class} object to print the
* class name of an object:
*
* <blockquote><pre>
* void printClassName(Object obj) {
* System.out.println("The class of " + obj +
* " is " + obj.getClass().getName());
* }
* </pre></blockquote>
*
* <p> It is also possible to get the {@code Class} object for a named
* type (or for void) using a class literal. See Section 15.8.2 of
* <cite>The Java™ Language Specification</cite>.
* For example:
*
* <blockquote>
* {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
* </blockquote>
*
* @param <T> the type of the class modeled by this {@code Class}
* object. For example, the type of {@code String.class} is {@code
* Class<String>}. Use {@code Class<?>} if the class being modeled is
* unknown.
*
* @author unascribed
* @see java.lang.ClassLoader#defineClass(byte[], int, int)
* @since 1.0
*/
// 反射元素-类/接口
public final class Class<T> implements Serializable, GenericDeclaration, Type, AnnotatedElement {
/** use serialVersionUID from JDK 1.1 for interoperability */
private static final long serialVersionUID = 3206093459760846163L;
private static final int ANNOTATION = 0x00002000;
private static final int ENUM = 0x00004000;
private static final int SYNTHETIC = 0x00001000;
/**
* Class Class is special cased within the Serialization Stream Protocol.
*
* A Class instance is written initially into an ObjectOutputStream in the
* following format:
* <pre>
* {@code TC_CLASS} ClassDescriptor
* A ClassDescriptor is a special cased serialization of
* a {@code java.io.ObjectStreamClass} instance.
* </pre>
* A new handle is generated for the initial time the class descriptor
* is written into the stream. Future references to the class descriptor
* are written as references to the initial class descriptor instance.
*
* @see java.io.ObjectStreamClass
*/
private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0];
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
/**
* Initialized in JVM not by private constructor
* This field is filtered from reflection access, i.e. getDeclaredField will throw NoSuchFieldException
*/
// 当前类关联的类加载器
private final ClassLoader classLoader;
// 数组的组件类型,int[]对应int,int[][]对应int[],不是数组则为null
private final Class<?> componentType;
/** protection domain returned when the internal domain is null */
private static ProtectionDomain allPermDomain;
private static ReflectionFactory reflectionFactory;
private transient volatile Constructor<T> cachedConstructor;
private transient volatile Class<?> newInstanceCallerCache;
private transient volatile SoftReference<ReflectionData<T>> reflectionData;
// Incremented by the VM on each call to JVM TI RedefineClasses() that redefines this class or a superclass.
private transient volatile int classRedefinedCount;
// Generic info repository; lazily initialized
private transient volatile ClassRepository genericInfo;
private transient volatile T[] enumConstants;
private transient volatile Map<String, T> enumConstantDirectory;
// Annotations cache
@SuppressWarnings("UnusedDeclaration")
private transient volatile AnnotationData annotationData;
@SuppressWarnings("UnusedDeclaration")
private transient volatile AnnotationType annotationType;
// cache the name to reduce the number of calls into the VM
private transient String name;
// set by VM
private transient Module module;
// cached package name
private transient String packageName;
/**
* Backing store of user-defined values pertaining to this class.
* Maintained by the ClassValue class.
*/
transient ClassValue.ClassValueMap classValueMap;
static {
registerNatives();
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Private constructor. Only the Java Virtual Machine creates Class objects.
* This constructor is not used and prevents the default constructor being generated.
*/
private Class(ClassLoader loader, Class<?> arrayComponentType) {
// Initialize final field for classLoader.
// The initialization value of non-null prevents future JIT optimizations from assuming this final field is null.
classLoader = loader;
componentType = arrayComponentType;
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 加载类 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the {@code Class} object associated with the class or
* interface with the given string name. Invoking this method is
* equivalent to:
*
* <blockquote>
* {@code Class.forName(className, true, currentLoader)}
* </blockquote>
*
* where {@code currentLoader} denotes the defining class loader of
* the current class.
*
* <p> For example, the following code fragment returns the
* runtime {@code Class} descriptor for the class named
* {@code java.lang.Thread}:
*
* <blockquote>
* {@code Class t = Class.forName("java.lang.Thread")}
* </blockquote>
* <p>
* A call to {@code forName("X")} causes the class named
* {@code X} to be initialized.
*
* @param className the fully qualified name of the desired class.
*
* @return the {@code Class} object for the class with the
* specified name.
*
* @throws LinkageError if the linkage fails
* @throws ExceptionInInitializerError if the initialization provoked
* by this method fails
* @throws ClassNotFoundException if the class cannot be located
*/
// 根据类的全名加载类对象,而且加载类之后对类的静态元素进行初始化
@CallerSensitive
public static Class<?> forName(String className) throws ClassNotFoundException {
Class<?> caller = Reflection.getCallerClass();
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}
/**
* Returns the {@code Class} object associated with the class or
* interface with the given string name, using the given class loader.
* Given the fully qualified name for a class or interface (in the same
* format returned by {@code getName}) this method attempts to
* locate, load, and link the class or interface. The specified class
* loader is used to load the class or interface. If the parameter
* {@code loader} is null, the class is loaded through the bootstrap
* class loader. The class is initialized only if the
* {@code initialize} parameter is {@code true} and if it has
* not been initialized earlier.
*
* <p> If {@code name} denotes a primitive type or void, an attempt
* will be made to locate a user-defined class in the unnamed package whose
* name is {@code name}. Therefore, this method cannot be used to
* obtain any of the {@code Class} objects representing primitive
* types or void.
*
* <p> If {@code name} denotes an array class, the component type of
* the array class is loaded but not initialized.
*
* <p> For example, in an instance method the expression:
*
* <blockquote>
* {@code Class.forName("Foo")}
* </blockquote>
*
* is equivalent to:
*
* <blockquote>
* {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
* </blockquote>
*
* Note that this method throws errors related to loading, linking or
* initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
* Java Language Specification</em>.
* Note that this method does not check whether the requested class
* is accessible to its caller.
*
* @param className fully qualified name of the desired class
* @param initialize if {@code true} the class will be initialized.
* See Section 12.4 of <em>The Java Language Specification</em>.
* @param loader class loader from which the class must be loaded
*
* @return class object representing the desired class
*
* @throws LinkageError if the linkage fails
* @throws ExceptionInInitializerError if the initialization provoked
* by this method fails
* @throws ClassNotFoundException if the class cannot be located by
* the specified class loader
* @throws SecurityException if a security manager is present, and the {@code loader} is
* {@code null}, and the caller's class loader is not
* {@code null}, and the caller does not have the
* {@link RuntimePermission}{@code ("getClassLoader")}
* @see java.lang.Class#forName(String)
* @see java.lang.ClassLoader
* @since 1.2
*/
// 根据类的全名和指定的类加载器加载类对象,initialize参数指示是否在加载类之后对类中的静态元素进行初始化
@CallerSensitive
public static Class<?> forName(String className, boolean initialize, ClassLoader loader) throws ClassNotFoundException {
Class<?> caller = null;
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
/*
* Reflective call to get caller class is only needed if a security manager is present.
* Avoid the overhead of making this call otherwise.
*/
caller = Reflection.getCallerClass();
if(loader == null) {
ClassLoader ccl = ClassLoader.getClassLoader(caller);
if(ccl != null) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
}
return forName0(className, initialize, loader, caller);
}
/**
* Returns the {@code Class} with the given <a href="ClassLoader.html#name">
* binary name</a> in the given module.
*
* <p> This method attempts to locate, load, and link the class or interface.
* It does not run the class initializer. If the class is not found, this
* method returns {@code null}. </p>
*
* <p> If the class loader of the given module defines other modules and
* the given name is a class defined in a different module, this method
* returns {@code null} after the class is loaded. </p>
*
* <p> This method does not check whether the requested class is
* accessible to its caller. </p>
*
* @param module A module
* @param name The <a href="ClassLoader.html#name">binary name</a>
* of the class
*
* @return {@code Class} object of the given name defined in the given module;
* {@code null} if not found.
*
* @throws NullPointerException if the given module or name is {@code null}
* @throws LinkageError if the linkage fails
* @throws SecurityException <ul>
* <li> if the caller is not the specified module and
* {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
* <li> access to the module content is denied. For example,
* permission check will be performed when a class loader calls
* {@link ModuleReader#open(String)} to read the bytes of a class file
* in a module.</li>
* </ul>
* @apiNote This method returns {@code null} on failure rather than
* throwing a {@link ClassNotFoundException}, as is done by
* the {@link #forName(String, boolean, ClassLoader)} method.
* The security check is a stack-based permission check if the caller
* loads a class in another module.
* @spec JPMS
* @since 9
*/
// 根据类的全名和所在的Module加载类对象(不会初始化),如果该module下没有该类,返回null
@CallerSensitive
public static Class<?> forName(Module module, String name) {
Objects.requireNonNull(module);
Objects.requireNonNull(name);
// 加载模块module的类加载器
ClassLoader cl;
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
Class<?> caller = Reflection.getCallerClass();
if(caller != null && caller.getModule() != module) {
// if caller is null, Class.forName is the last java frame on the stack. java.base has all permissions
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
PrivilegedAction<ClassLoader> pa = module::getClassLoader;
cl = AccessController.doPrivileged(pa);
} else {
cl = module.getClassLoader();
}
// 处理BootClassLoader情形
if(cl == null) {
// 通过bootstrap类加载器查找类是否已加载,如果找不到则返回null
return BootLoader.loadClass(module, name);
} else {
// 根据给定的模块名与类的全名加载类
return cl.loadClass(module, name);
}
}
/*▲ 加载类 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 创建对象 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a new instance of the class represented by this {@code Class} object.
* The class is instantiated as if by a {@code new} expression with an empty argument list.
* The class is initialized if it has not already been initialized.
*
* @return a newly allocated instance of the class represented by this object.
*
* @throws IllegalAccessException if the class or its nullary
* constructor is not accessible.
* @throws InstantiationException if this {@code Class} represents an abstract class,
* an interface, an array class, a primitive type, or void;
* or if the class has no nullary constructor;
* or if the instantiation fails for some other reason.
* @throws ExceptionInInitializerError if the initialization
* provoked by this method fails.
* @throws SecurityException If a security manager, <i>s</i>, is present and
* the caller's class loader is not the same as or an
* ancestor of the class loader for the current class and
* invocation of {@link SecurityManager#checkPackageAccess
* s.checkPackageAccess()} denies access to the package
* of this class.
* @deprecated This method propagates any exception thrown by the nullary constructor, including a checked exception.
* Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler.
* The {@link java.lang.reflect.Constructor#newInstance(java.lang.Object...) Constructor.newInstance} method avoids this problem
* by wrapping any exception thrown by the constructor in a (checked) {@link java.lang.reflect.InvocationTargetException}.
*
* <p>The call
*
* <pre>{@code
* clazz.newInstance()
* }</pre>
*
* can be replaced by
*
* <pre>{@code
* clazz.getDeclaredConstructor().newInstance()
* }</pre>
*
* The latter sequence of calls is inferred to be able to throw the additional exception types {@link InvocationTargetException} and {@link NoSuchMethodException}.
* Both of these exception types are subclasses of {@link ReflectiveOperationException}.
*/
// 创建当前类的对象(该方法已过时,不再建议使用)
@CallerSensitive
@Deprecated(since = "9")
public T newInstance() throws InstantiationException, IllegalAccessException {
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
}
/* NOTE: the following code may not be strictly correct under the current Java memory model. */
// Constructor lookup
if(cachedConstructor == null) {
if(this == Class.class) {
throw new IllegalAccessException("Can not call newInstance() on the Class for java.lang.Class");
}
try {
Class<?>[] empty = {};
final Constructor<T> c = getReflectionFactory().copyConstructor(getConstructor0(empty, Member.DECLARED));
/*
* Disable accessibility checks on the constructor since we have to do the security check here anyway
* (the stack depth is wrong for the Constructor's security check to work)
*/
AccessController.doPrivileged(new PrivilegedAction<>() {
public Void run() {
c.setAccessible(true);
return null;
}
});
cachedConstructor = c;
} catch(NoSuchMethodException e) {
throw (InstantiationException) new InstantiationException(getName()).initCause(e);
}
}
Constructor<T> tmpConstructor = cachedConstructor;
// Security check (same as in java.lang.reflect.Constructor)
Class<?> caller = Reflection.getCallerClass();
if(newInstanceCallerCache != caller) {
int modifiers = tmpConstructor.getModifiers();
Reflection.ensureMemberAccess(caller, this, this, modifiers);
newInstanceCallerCache = caller;
}
// Run constructor
try {
return tmpConstructor.newInstance((Object[]) null);
} catch(InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
}
/*▲ 创建对象 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 获取类名 ████████████████████████████████████████████████████████████████████████████████┓ */
/* 参见ClassTest文件夹中com.kang.clazz.test02下的测试类 */
/**
* Returns the name of the entity (class, interface, array class,
* primitive type, or void) represented by this {@code Class} object,
* as a {@code String}.
*
* <p> If this class object represents a reference type that is not an
* array type then the binary name of the class is returned, as specified
* by
* <cite>The Java™ Language Specification</cite>.
*
* <p> If this class object represents a primitive type or void, then the
* name returned is a {@code String} equal to the Java language
* keyword corresponding to the primitive type or void.
*
* <p> If this class object represents a class of arrays, then the internal
* form of the name consists of the name of the element type preceded by
* one or more '{@code [}' characters representing the depth of the array
* nesting. The encoding of element type names is as follows:
*
* <blockquote><table class="striped">
* <caption style="display:none">Element types and encodings</caption>
* <thead>
* <tr><th scope="col"> Element Type <th scope="col"> Encoding
* </thead>
* <tbody style="text-align:left">
* <tr><th scope="row"> boolean <td style="text-align:center"> Z
* <tr><th scope="row"> byte <td style="text-align:center"> B
* <tr><th scope="row"> char <td style="text-align:center"> C
* <tr><th scope="row"> class or interface
* <td style="text-align:center"> L<i>classname</i>;
* <tr><th scope="row"> double <td style="text-align:center"> D
* <tr><th scope="row"> float <td style="text-align:center"> F
* <tr><th scope="row"> int <td style="text-align:center"> I
* <tr><th scope="row"> long <td style="text-align:center"> J
* <tr><th scope="row"> short <td style="text-align:center"> S
* </tbody>
* </table></blockquote>
*
* <p> The class or interface name <i>classname</i> is the binary name of
* the class specified above.
*
* <p> Examples:
* <blockquote><pre>
* String.class.getName()
* returns "java.lang.String"
* byte.class.getName()
* returns "byte"
* (new Object[3]).getClass().getName()
* returns "[Ljava.lang.Object;"
* (new int[3][4][5][6][7][8][9]).getClass().getName()
* returns "[[[[[[[I"
* </pre></blockquote>
*
* @return the name of the class or interface
* represented by this object.
*/
/*
* 虚拟机中呈现的名称
*
* char 基本类型
* [C 基本类型数组
* com.kang.Outer 引用类型
* [Lcom.kang.Outer; 引用类型数组
* com.kang.Outer$Inner 内部类
* com.kang.Outer$1 匿名类
* com.kang.Outer$$Lambda$1/1989780873 Lambda表达式
*/
public String getName() {
String name = this.name;
if(name == null) {
this.name = name = getName0();
}
return name;
}
/**
* Returns the canonical name of the underlying class as
* defined by the Java Language Specification. Returns null if
* the underlying class does not have a canonical name (i.e., if
* it is a local or anonymous class or an array whose component
* type does not have a canonical name).
*
* @return the canonical name of the underlying class if it exists, and
* {@code null} otherwise.
*
* @since 1.5
*/
/*
* 规范名称,尽量遵从书写习惯(匿名类为null)
*
* char 基本类型
* char[] 基本类型数组
* com.kang.Outer 引用类型
* com.kang.Outer[] 引用类型数组
* com.kang.Outer.Inner 内部类
* null 匿名类
* com.kang.Outer$$Lambda$1/1989780873 Lambda表达式
*/
public String getCanonicalName() {
ReflectionData<T> rd = reflectionData();
String canonicalName = rd.canonicalName;
if(canonicalName == null) {
rd.canonicalName = canonicalName = getCanonicalName0();
}
return canonicalName == ReflectionData.NULL_SENTINEL ? null : canonicalName;
}
/**
* Returns the simple name of the underlying class as given in the
* source code. Returns an empty string if the underlying class is
* anonymous.
*
* <p>The simple name of an array is the simple name of the
* component type with "[]" appended. In particular the simple
* name of an array whose component type is anonymous is "[]".
*
* @return the simple name of the underlying class
*
* @since 1.5
*/
/*
* 简单名称,可以看做是不带包名和外部类名的规范名(匿名类没有)
*
* char 基本类型
* char[] 基本类型数组
* Outer 引用类型
* Outer[] 引用类型数组
* Inner 内部类
* 匿名类
* Outer$$Lambda$1/1989780873 Lambda表达式
*/
public String getSimpleName() {
ReflectionData<T> rd = reflectionData();
String simpleName = rd.simpleName;
if(simpleName == null) {
rd.simpleName = simpleName = getSimpleName0();
}
return simpleName;
}
/**
* Return an informative string for the name of this type.
*
* @return an informative string for the name of this type
*
* @since 1.8
*/
/*
* 类型名称
*
* char 基本类型
* char[] 基本类型数组
* com.kang.Outer 引用类型
* com.kang.Outer[] 引用类型数组
* com.kang.Outer$Inner 内部类
* com.kang.Outer$1 匿名类
* com.kang.Outer$$Lambda$1/1989780873 Lambda表达式
*/
public String getTypeName() {
if(isArray()) {
try {
Class<?> cl = this;
int dimensions = 0;
do {
dimensions++;
cl = cl.getComponentType();
} while(cl.isArray());
StringBuilder sb = new StringBuilder();
sb.append(cl.getName());
for(int i = 0; i<dimensions; i++) {
sb.append("[]");
}
return sb.toString();
} catch(Throwable e) { /*FALLTHRU*/ }
}
return getName();
}
/*▲ 获取类名 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ isXXX ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Determines if the specified {@code Object} is assignment-compatible
* with the object represented by this {@code Class}. This method is
* the dynamic equivalent of the Java language {@code instanceof}
* operator. The method returns {@code true} if the specified
* {@code Object} argument is non-null and can be cast to the
* reference type represented by this {@code Class} object without
* raising a {@code ClassCastException.} It returns {@code false}
* otherwise.
*
* <p> Specifically, if this {@code Class} object represents a
* declared class, this method returns {@code true} if the specified
* {@code Object} argument is an instance of the represented class (or
* of any of its subclasses); it returns {@code false} otherwise. If
* this {@code Class} object represents an array class, this method
* returns {@code true} if the specified {@code Object} argument
* can be converted to an object of the array class by an identity
* conversion or by a widening reference conversion; it returns
* {@code false} otherwise. If this {@code Class} object
* represents an interface, this method returns {@code true} if the
* class or any superclass of the specified {@code Object} argument
* implements this interface; it returns {@code false} otherwise. If
* this {@code Class} object represents a primitive type, this method
* returns {@code false}.
*
* @param obj the object to check
*
* @return true if {@code obj} is an instance of this class
*
* @since 1.1
*/
/*
* X.class.isInstance(obj) ==> 判断[对象]obj是否可以作为X类的实例
* obj instanceof X 与上述调用作用一致
* 关键字instanceof更简洁,isInstance()方法更灵活
*/
@HotSpotIntrinsicCandidate
public native boolean isInstance(Object obj);
/**
* Determines if the class or interface represented by this
* {@code Class} object is either the same as, or is a superclass or
* superinterface of, the class or interface represented by the specified
* {@code Class} parameter. It returns {@code true} if so;
* otherwise it returns {@code false}. If this {@code Class}
* object represents a primitive type, this method returns
* {@code true} if the specified {@code Class} parameter is
* exactly this {@code Class} object; otherwise it returns
* {@code false}.
*
* <p> Specifically, this method tests whether the type represented by the
* specified {@code Class} parameter can be converted to the type
* represented by this {@code Class} object via an identity conversion
* or via a widening reference conversion. See <em>The Java Language
* Specification</em>, sections 5.1.1 and 5.1.4 , for details.
*
* @param cls the {@code Class} object to be checked
*
* @return the {@code boolean} value indicating whether objects of the
* type {@code cls} can be assigned to objects of this class
*
* @throws NullPointerException if the specified Class parameter is
* null.
* @since 1.1
*/
/*
* X.class.isAssignableFrom(cls) ==> 判断cls类型的对象是否为X类型的实例
* 即判断X与cls所属的类/接口是否相同,或者X是cls的父类/父接口
*/
@HotSpotIntrinsicCandidate
public native boolean isAssignableFrom(Class<?> cls);
/**
* Determines if the specified {@code Class} object represents an
* interface type.
*
* @return {@code true} if this object represents an interface;
* {@code false} otherwise.
*/
// X.class.isInterface() ==> 判断X是否为接口
@HotSpotIntrinsicCandidate
public native boolean isInterface();
/**
* Returns true if this {@code Class} object represents an annotation
* type. Note that if this method returns true, {@link #isInterface()}
* would also return true, as all annotation types are also interfaces.
*
* @return {@code true} if this class object represents an annotation
* type; {@code false} otherwise
*
* @since 1.5
*/
// X.class.isAnnotation() ==> 判断X是否为注解类,如果成立,则X.class.isInterface()也返回true
public boolean isAnnotation() {
return (getModifiers() & ANNOTATION) != 0;
}
/**
* Determines if the specified {@code Class} object represents a
* primitive type.
*
* <p> There are nine predefined {@code Class} objects to represent
* the eight primitive types and void. These are created by the Java
* Virtual Machine, and have the same names as the primitive types that
* they represent, namely {@code boolean}, {@code byte},
* {@code char}, {@code short}, {@code int},
* {@code long}, {@code float}, and {@code double}.
*
* <p> These objects may only be accessed via the following public static
* final variables, and are the only {@code Class} objects for which
* this method returns {@code true}.
*
* @return true if and only if this class represents a primitive type
*
* @see java.lang.Boolean#TYPE
* @see java.lang.Character#TYPE
* @see java.lang.Byte#TYPE
* @see java.lang.Short#TYPE
* @see java.lang.Integer#TYPE
* @see java.lang.Long#TYPE
* @see java.lang.Float#TYPE
* @see java.lang.Double#TYPE
* @see java.lang.Void#TYPE
* @since 1.1
*/
// X.class.isPrimitive() ==> 判断X是否为基本类型,如int.class
@HotSpotIntrinsicCandidate
public native boolean isPrimitive();
/**
* Determines if this {@code Class} object represents an array class.
*
* @return {@code true} if this object represents an array class;
* {@code false} otherwise.
*
* @since 1.1
*/
// X.class.isArray() ==> 判断X是否为数组
@HotSpotIntrinsicCandidate
public native boolean isArray();
/**
* Returns true if and only if this class was declared as an enum in the
* source code.
*
* @return true if and only if this class was declared as an enum in the
* source code
*
* @since 1.5
*/
// X.class.isEnum() ==> 判断X是否为枚举
public boolean isEnum() {
// An enum must both directly extend java.lang.Enum and have the ENUM bit set;
// classes for specialized enum constants don't do the former.
return (this.getModifiers() & ENUM) != 0 && this.getSuperclass() == java.lang.Enum.class;
}
/**
* Returns {@code true} if and only if the underlying class is an anonymous class.
*
* @return {@code true} if and only if this class is an anonymous class.
*
* @since 1.5
*/
// X.class.isAnonymousClass() ==> 判断X是否为匿名类
public boolean isAnonymousClass() {
return !isArray() && isLocalOrAnonymousClass() && getSimpleBinaryName0() == null;
}
/**
* Returns {@code true} if and only if the underlying class
* is a local class.
*
* @return {@code true} if and only if this class is a local class.
*
* @since 1.5
*/
// X.class.isLocalClass() ==> 判断X是否为方法内部类
public boolean isLocalClass() {
return isLocalOrAnonymousClass() && (isArray() || getSimpleBinaryName0() != null);
}
/**
* Returns {@code true} if and only if the underlying class
* is a member class.
*
* @return {@code true} if and only if this class is a member class.
*
* @since 1.5
*/
// X.class.isMemberClass() ==> 判断X是否为成员内部类
public boolean isMemberClass() {
return !isLocalOrAnonymousClass() && getDeclaringClass0() != null;
}
/**
* Returns {@code true} if this class is a synthetic class;
* returns {@code false} otherwise.
*
* @return {@code true} if and only if this class is a synthetic class as
* defined by the Java Language Specification.
*
* @jls 13.1 The Form of a Binary
* @since 1.5
*/
// 合成类,一般是代理形式。如((Runnable) () -> {}).getClass().isSynthetic()为true
public boolean isSynthetic() {
return (getModifiers() & SYNTHETIC) != 0;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException {@inheritDoc}
* @since 1.5
*/
// 判断当前类上是否存在注解类型annotationClass,要求注解类型annotationClass运行时可见(@Retention(RetentionPolicy.RUNTIME))
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
return GenericDeclaration.super.isAnnotationPresent(annotationClass);
}
/*▲ isXXX ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ Class ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the {@code Class} representing the component type of an
* array. If this class does not represent an array class this method
* returns null.
*
* @return the {@code Class} representing the component type of this
* class if this class is an array
*
* @see java.lang.reflect.Array
* @since 1.1
*/
// 获取数组的组件类型,如int[]返回int,int[][]返回int[]。如果不是数组,则返回空
public Class<?> getComponentType() {
// Only return for array types. Storage may be reused for Class for instance types.
if(isArray()) {