/
ClassInfo.java
3086 lines (2851 loc) · 129 KB
/
ClassInfo.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
/*
* This file is part of ClassGraph.
*
* Author: Luke Hutchison
*
* Hosted at: https://github.com/classgraph/classgraph
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Luke Hutchison
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.classgraph;
import java.io.File;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import io.github.classgraph.Classfile.ClassContainment;
import io.github.classgraph.Classfile.ClassTypeAnnotationDecorator;
import nonapi.io.github.classgraph.json.Id;
import nonapi.io.github.classgraph.scanspec.ScanSpec;
import nonapi.io.github.classgraph.types.ParseException;
import nonapi.io.github.classgraph.types.Parser;
import nonapi.io.github.classgraph.types.TypeUtils;
import nonapi.io.github.classgraph.types.TypeUtils.ModifierType;
import nonapi.io.github.classgraph.utils.LogNode;
/** Holds metadata about a class encountered during a scan. */
public class ClassInfo extends ScanResultObject implements Comparable<ClassInfo>, HasName {
/** The name of the class. */
@Id
protected String name;
/** Class modifier flags, e.g. Modifier.PUBLIC */
private int modifiers;
/** True if the class is a record. */
private boolean isRecord;
/**
* This annotation has the {@link Inherited} meta-annotation, which means that any class that this annotation is
* applied to also implicitly causes the annotation to annotate all subclasses too.
*/
boolean isInherited;
/** The minor version of the classfile format for this class' classfile. */
private int classfileMinorVersion;
/** The major version of the classfile format for this class' classfile. */
private int classfileMajorVersion;
/** The class type signature string. */
protected String typeSignatureStr;
/** The class type signature, parsed. */
private transient ClassTypeSignature typeSignature;
/** The fully-qualified defining method name, for anonymous inner classes. */
private String fullyQualifiedDefiningMethodName;
/**
* If true, this class is only being referenced by another class' classfile as a superclass / implemented
* interface / annotation, but this class is not itself an accepted (non-rejected) class, or in a accepted
* (non-rejected) package.
*
* If false, this classfile was matched during scanning (i.e. its classfile contents read), i.e. this class is a
* accepted (and non-rejected) class in an accepted (and non-rejected) package.
*/
protected boolean isExternalClass = true;
/**
* Set to true when the class is actually scanned (as opposed to just referenced as a superclass, interface or
* annotation of a scanned class).
*/
protected boolean isScannedClass;
/** The classpath element that this class was found within. */
transient ClasspathElement classpathElement;
/** The {@link Resource} for the classfile of this class. */
protected transient Resource classfileResource;
/** The classloader this class was obtained from. */
transient ClassLoader classLoader;
/** Info on the class module. */
ModuleInfo moduleInfo;
/** Info on the package containing the class. */
PackageInfo packageInfo;
/** Info on class annotations, including optional annotation param values. */
AnnotationInfoList annotationInfo;
/** Info on fields. */
FieldInfoList fieldInfo;
/** Info on fields. */
MethodInfoList methodInfo;
/** For annotations, the default values of parameters. */
AnnotationParameterValueList annotationDefaultParamValues;
/** The type annotation decorators for the {@link ClassTypeSignature} instance. */
List<ClassTypeAnnotationDecorator> typeAnnotationDecorators;
/**
* Names of classes referenced by this class in class refs and type signatures in the constant pool of the
* classfile.
*/
private Set<String> referencedClassNames;
/**
* A list of ClassInfo objects for classes referenced by this class. Derived from {@link #referencedClassNames}
* when the relevant {@link ClassInfo} objects are created.
*/
private ClassInfoList referencedClasses;
/**
* Set to true once any Object[] arrays of boxed types in annotationDefaultParamValues have been lazily
* converted to primitive arrays.
*/
transient boolean annotationDefaultParamValuesHasBeenConvertedToPrimitive;
/** The set of classes related to this one. */
private Map<RelType, Set<ClassInfo>> relatedClasses;
/**
* The override order for a class' fields or methods (base class, followed by interfaces, followed by
* superclasses).
*/
private transient List<ClassInfo> overrideOrder;
// -------------------------------------------------------------------------------------------------------------
/** The modifier bit for annotations. */
private static final int ANNOTATION_CLASS_MODIFIER = 0x2000;
/** The constant empty return value used when no classes are reachable. */
private static final ReachableAndDirectlyRelatedClasses NO_REACHABLE_CLASSES = //
new ReachableAndDirectlyRelatedClasses(Collections.<ClassInfo> emptySet(),
Collections.<ClassInfo> emptySet());
// -------------------------------------------------------------------------------------------------------------
/** Default constructor for deserialization. */
ClassInfo() {
super();
}
/**
* Constructor.
*
* @param name
* the name
* @param classModifiers
* the class modifiers
* @param classfileResource
* the classfile resource
*/
@SuppressWarnings("null")
protected ClassInfo(final String name, final int classModifiers, final Resource classfileResource) {
super();
this.name = name;
if (name.endsWith(";")) {
// Spot check to make sure class names were parsed from descriptors
throw new IllegalArgumentException("Bad class name");
}
setModifiers(classModifiers);
this.classfileResource = classfileResource;
this.relatedClasses = new EnumMap<>(RelType.class);
}
// -------------------------------------------------------------------------------------------------------------
/** How classes are related. */
enum RelType {
// Classes:
/**
* Superclasses of this class, if this is a regular class.
*
* <p>
* (Should consist of only one entry, or null if superclass is java.lang.Object or unknown).
*/
SUPERCLASSES,
/** Subclasses of this class, if this is a regular class. */
SUBCLASSES,
/** Indicates that an inner class is contained within this one. */
CONTAINS_INNER_CLASS,
/** Indicates that an outer class contains this one. (Should only have zero or one entries.) */
CONTAINED_WITHIN_OUTER_CLASS,
// Interfaces:
/**
* Interfaces that this class implements, if this is a regular class, or superinterfaces, if this is an
* interface.
*
* <p>
* (May also include annotations, since annotations are interfaces, so you can implement an annotation.)
*/
IMPLEMENTED_INTERFACES,
/**
* Classes that implement this interface (including sub-interfaces), if this is an interface.
*/
CLASSES_IMPLEMENTING,
// Class annotations:
/**
* Annotations on this class, if this is a regular class, or meta-annotations on this annotation, if this is
* an annotation.
*/
CLASS_ANNOTATIONS,
/** Classes annotated with this annotation, if this is an annotation. */
CLASSES_WITH_ANNOTATION,
// Method annotations:
/** Annotations on one or more methods of this class. */
METHOD_ANNOTATIONS,
/**
* Classes that have one or more methods annotated with this annotation, if this is an annotation.
*/
CLASSES_WITH_METHOD_ANNOTATION,
/**
* Classes that have one or more non-private (inherited) methods annotated with this annotation, if this is
* an annotation.
*/
CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION,
/** Annotations on one or more parameters of methods of this class. */
METHOD_PARAMETER_ANNOTATIONS,
/**
* Classes that have one or more methods that have one or more parameters annotated with this annotation, if
* this is an annotation.
*/
CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
/**
* Classes that have one or more non-private (inherited) methods that have one or more parameters annotated
* with this annotation, if this is an annotation.
*/
CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION,
// Field annotations:
/** Annotations on one or more fields of this class. */
FIELD_ANNOTATIONS,
/**
* Classes that have one or more fields annotated with this annotation, if this is an annotation.
*/
CLASSES_WITH_FIELD_ANNOTATION,
/**
* Classes that have one or more non-private (inherited) fields annotated with this annotation, if this is
* an annotation.
*/
CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION,
}
/**
* Add a class with a given relationship type. Return whether the collection changed as a result of the call.
*
* @param relType
* the {@link RelType}
* @param classInfo
* the {@link ClassInfo}
* @return true, if successful
*/
boolean addRelatedClass(final RelType relType, final ClassInfo classInfo) {
Set<ClassInfo> classInfoSet = relatedClasses.get(relType);
if (classInfoSet == null) {
relatedClasses.put(relType, classInfoSet = new LinkedHashSet<>(4));
}
return classInfoSet.add(classInfo);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get a ClassInfo object, or create it if it doesn't exist. N.B. not threadsafe, so ClassInfo objects should
* only ever be constructed by a single thread.
*
* @param className
* the class name
* @param classNameToClassInfo
* the map from class name to class info
* @return the {@link ClassInfo} object.
*/
static ClassInfo getOrCreateClassInfo(final String className,
final Map<String, ClassInfo> classNameToClassInfo) {
// Look for array class names
int numArrayDims = 0;
String baseClassName = className;
while (baseClassName.endsWith("[]")) {
numArrayDims++;
baseClassName = baseClassName.substring(0, baseClassName.length() - 2);
}
// Be resilient to the use of class descriptors rather than class names (should not be needed)
while (baseClassName.startsWith("[")) {
numArrayDims++;
baseClassName = baseClassName.substring(1);
}
if (baseClassName.endsWith(";")) {
baseClassName = baseClassName.substring(baseClassName.length() - 1);
}
baseClassName = baseClassName.replace('/', '.');
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
if (numArrayDims == 0) {
classInfo = new ClassInfo(baseClassName, /* classModifiers = */ 0, /* classfileResource = */ null);
} else {
final StringBuilder arrayTypeSigStrBuf = new StringBuilder();
for (int i = 0; i < numArrayDims; i++) {
arrayTypeSigStrBuf.append('[');
}
TypeSignature elementTypeSignature;
final char baseTypeChar = BaseTypeSignature.getTypeChar(baseClassName);
if (baseTypeChar != '\0') {
// Element type is a base (primitive) type
arrayTypeSigStrBuf.append(baseTypeChar);
elementTypeSignature = new BaseTypeSignature(baseTypeChar);
} else {
// Element type is not a base (primitive) type -- create a type signature for element type
final String eltTypeSigStr = "L" + baseClassName.replace('.', '/') + ";";
arrayTypeSigStrBuf.append(eltTypeSigStr);
try {
elementTypeSignature = ClassRefTypeSignature.parse(new Parser(eltTypeSigStr),
// No type variables to resolve for generic types
/* definingClassName = */ null);
if (elementTypeSignature == null) {
throw new IllegalArgumentException(
"Could not form array base type signature for class " + baseClassName);
}
} catch (final ParseException e) {
throw new IllegalArgumentException(
"Could not form array base type signature for class " + baseClassName);
}
}
classInfo = new ArrayClassInfo(
new ArrayTypeSignature(elementTypeSignature, numArrayDims, arrayTypeSigStrBuf.toString()));
}
classNameToClassInfo.put(className, classInfo);
}
return classInfo;
}
/**
* Set classfile version.
*
* @param minorVersion
* the minor version of the classfile format for this class' classfile.
* @param majorVersion
* the major version of the classfile format for this class' classfile.
*/
void setClassfileVersion(final int minorVersion, final int majorVersion) {
this.classfileMinorVersion = minorVersion;
this.classfileMajorVersion = majorVersion;
}
/**
* Set class modifiers.
*
* @param modifiers
* the class modifiers
*/
void setModifiers(final int modifiers) {
this.modifiers |= modifiers;
}
/**
* Set isInterface status.
*
* @param isInterface
* true if this is an interface
*/
void setIsInterface(final boolean isInterface) {
if (isInterface) {
this.modifiers |= Modifier.INTERFACE;
}
}
/**
* Set isAnnotation status.
*
* @param isAnnotation
* true if this is an annotation
*/
void setIsAnnotation(final boolean isAnnotation) {
if (isAnnotation) {
this.modifiers |= ANNOTATION_CLASS_MODIFIER;
}
}
/**
* Set isRecord status.
*
* @param isRecord
* true if this is a record
*/
void setIsRecord(final boolean isRecord) {
if (isRecord) {
this.isRecord = isRecord;
}
}
/**
* Add {@link ClassTypeAnnotationDecorator} instances.
*
* @param classTypeAnnotationDecorators
* {@link ClassTypeAnnotationDecorator} instances.
*/
void addTypeDecorators(final List<ClassTypeAnnotationDecorator> classTypeAnnotationDecorators) {
if (typeAnnotationDecorators == null) {
typeAnnotationDecorators = new ArrayList<>();
}
typeAnnotationDecorators.addAll(classTypeAnnotationDecorators);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Add a superclass to this class.
*
* @param superclassName
* the superclass name
* @param classNameToClassInfo
* the map from class name to class info
*/
void addSuperclass(final String superclassName, final Map<String, ClassInfo> classNameToClassInfo) {
if (superclassName != null && !superclassName.equals("java.lang.Object")) {
final ClassInfo superclassClassInfo = getOrCreateClassInfo(superclassName, classNameToClassInfo);
this.addRelatedClass(RelType.SUPERCLASSES, superclassClassInfo);
superclassClassInfo.addRelatedClass(RelType.SUBCLASSES, this);
}
}
/**
* Add an implemented interface to this class.
*
* @param interfaceName
* the interface name
* @param classNameToClassInfo
* the map from class name to class info
*/
void addImplementedInterface(final String interfaceName, final Map<String, ClassInfo> classNameToClassInfo) {
final ClassInfo interfaceClassInfo = getOrCreateClassInfo(interfaceName, classNameToClassInfo);
interfaceClassInfo.setIsInterface(true);
this.addRelatedClass(RelType.IMPLEMENTED_INTERFACES, interfaceClassInfo);
interfaceClassInfo.addRelatedClass(RelType.CLASSES_IMPLEMENTING, this);
}
/**
* Add class containment info.
*
* @param classContainmentEntries
* the class containment entries
* @param classNameToClassInfo
* the map from class name to class info
*/
static void addClassContainment(final List<ClassContainment> classContainmentEntries,
final Map<String, ClassInfo> classNameToClassInfo) {
for (final ClassContainment classContainment : classContainmentEntries) {
final ClassInfo innerClassInfo = ClassInfo.getOrCreateClassInfo(classContainment.innerClassName,
classNameToClassInfo);
innerClassInfo.setModifiers(classContainment.innerClassModifierBits);
final ClassInfo outerClassInfo = ClassInfo.getOrCreateClassInfo(classContainment.outerClassName,
classNameToClassInfo);
innerClassInfo.addRelatedClass(RelType.CONTAINED_WITHIN_OUTER_CLASS, outerClassInfo);
outerClassInfo.addRelatedClass(RelType.CONTAINS_INNER_CLASS, innerClassInfo);
}
}
/**
* Add containing method name, for anonymous inner classes.
*
* @param fullyQualifiedDefiningMethodName
* the fully qualified defining method name
*/
void addFullyQualifiedDefiningMethodName(final String fullyQualifiedDefiningMethodName) {
this.fullyQualifiedDefiningMethodName = fullyQualifiedDefiningMethodName;
}
/**
* Add an annotation to this class.
*
* @param classAnnotationInfo
* the class annotation info
* @param classNameToClassInfo
* the map from class name to class info
*/
void addClassAnnotation(final AnnotationInfo classAnnotationInfo,
final Map<String, ClassInfo> classNameToClassInfo) {
final ClassInfo annotationClassInfo = getOrCreateClassInfo(classAnnotationInfo.getName(),
classNameToClassInfo);
annotationClassInfo.setModifiers(ANNOTATION_CLASS_MODIFIER);
if (this.annotationInfo == null) {
this.annotationInfo = new AnnotationInfoList(2);
}
this.annotationInfo.add(classAnnotationInfo);
this.addRelatedClass(RelType.CLASS_ANNOTATIONS, annotationClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_ANNOTATION, this);
// Record use of @Inherited meta-annotation
if (classAnnotationInfo.getName().equals(Inherited.class.getName())) {
isInherited = true;
}
}
/**
* Add field or method annotation cross-links.
*
* @param annotationInfoList
* the annotation info list
* @param isField
* the is field
* @param modifiers
* the field or method modifiers
* @param classNameToClassInfo
* the map from class name to class info
*/
private void addFieldOrMethodAnnotationInfo(final AnnotationInfoList annotationInfoList, final boolean isField,
final int modifiers, final Map<String, ClassInfo> classNameToClassInfo) {
if (annotationInfoList != null) {
for (final AnnotationInfo fieldAnnotationInfo : annotationInfoList) {
final ClassInfo annotationClassInfo = getOrCreateClassInfo(fieldAnnotationInfo.getName(),
classNameToClassInfo);
annotationClassInfo.setModifiers(ANNOTATION_CLASS_MODIFIER);
// Mark this class as having a field or method with this annotation
this.addRelatedClass(isField ? RelType.FIELD_ANNOTATIONS : RelType.METHOD_ANNOTATIONS,
annotationClassInfo);
annotationClassInfo.addRelatedClass(
isField ? RelType.CLASSES_WITH_FIELD_ANNOTATION : RelType.CLASSES_WITH_METHOD_ANNOTATION,
this);
// For non-private methods/fields, also add to nonprivate (inherited) mapping
if (!Modifier.isPrivate(modifiers)) {
annotationClassInfo.addRelatedClass(isField ? RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION
: RelType.CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION, this);
}
}
}
}
/**
* Add field info.
*
* @param fieldInfoList
* the field info list
* @param classNameToClassInfo
* the map from class name to class info
*/
void addFieldInfo(final FieldInfoList fieldInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final FieldInfo fi : fieldInfoList) {
// Index field annotations
addFieldOrMethodAnnotationInfo(fi.annotationInfo, /* isField = */ true, fi.getModifiers(),
classNameToClassInfo);
}
if (this.fieldInfo == null) {
this.fieldInfo = fieldInfoList;
} else {
this.fieldInfo.addAll(fieldInfoList);
}
}
/**
* Add method info.
*
* @param methodInfoList
* the method info list
* @param classNameToClassInfo
* the map from class name to class info
*/
void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final MethodInfo mi : methodInfoList) {
// Index method annotations
addFieldOrMethodAnnotationInfo(mi.annotationInfo, /* isField = */ false, mi.getModifiers(),
classNameToClassInfo);
// Index method parameter annotations
if (mi.parameterAnnotationInfo != null) {
for (int i = 0; i < mi.parameterAnnotationInfo.length; i++) {
final AnnotationInfo[] paramAnnotationInfoArr = mi.parameterAnnotationInfo[i];
if (paramAnnotationInfoArr != null) {
for (int j = 0; j < paramAnnotationInfoArr.length; j++) {
final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr[j];
final ClassInfo annotationClassInfo = getOrCreateClassInfo(
methodParamAnnotationInfo.getName(), classNameToClassInfo);
annotationClassInfo.setModifiers(ANNOTATION_CLASS_MODIFIER);
this.addRelatedClass(RelType.METHOD_PARAMETER_ANNOTATIONS, annotationClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
this);
// For non-private methods/fields, also add to nonprivate (inherited) mapping
if (!Modifier.isPrivate(mi.getModifiers())) {
annotationClassInfo.addRelatedClass(
RelType.CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION, this);
}
}
}
}
}
}
if (this.methodInfo == null) {
this.methodInfo = methodInfoList;
} else {
this.methodInfo.addAll(methodInfoList);
}
}
/**
* Set the class type signature, including any type params.
*
* @param typeSignatureStr
* the type signature str
*/
void setTypeSignature(final String typeSignatureStr) {
this.typeSignatureStr = typeSignatureStr;
}
/**
* Add annotation default values. (Only called in the case of annotation class definitions, when the annotation
* has default parameter values.)
*
* @param paramNamesAndValues
* the default param names and values, if this is an annotation
*/
void addAnnotationParamDefaultValues(final AnnotationParameterValueList paramNamesAndValues) {
setIsAnnotation(true);
if (this.annotationDefaultParamValues == null) {
this.annotationDefaultParamValues = paramNamesAndValues;
} else {
this.annotationDefaultParamValues.addAll(paramNamesAndValues);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Add a class that has just been scanned (as opposed to just referenced by a scanned class). Not threadsafe,
* should be run in single threaded context.
*
* @param className
* the class name
* @param classModifiers
* the class modifiers
* @param isExternalClass
* true if this is an external class
* @param classNameToClassInfo
* the map from class name to class info
* @param classpathElement
* the classpath element
* @param classfileResource
* the classfile resource
* @return the class info
*/
static ClassInfo addScannedClass(final String className, final int classModifiers,
final boolean isExternalClass, final Map<String, ClassInfo> classNameToClassInfo,
final ClasspathElement classpathElement, final Resource classfileResource) {
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
// This is the first time this class has been seen, add it
classNameToClassInfo.put(className,
classInfo = new ClassInfo(className, classModifiers, classfileResource));
} else {
// There was a previous placeholder ClassInfo class added, due to the class being referred
// to as a superclass, interface or annotation. The isScannedClass field should be false
// in this case, since the actual class definition wasn't reached before now.
if (classInfo.isScannedClass) {
// The class should not have been scanned more than once, because of classpath masking
throw new IllegalArgumentException("Class " + className
+ " should not have been encountered more than once due to classpath masking --"
+ " please report this bug at: https://github.com/classgraph/classgraph/issues");
}
// Set the classfileResource for the placeholder class
classInfo.classfileResource = classfileResource;
// Add any additional modifier bits
classInfo.modifiers |= classModifiers;
}
// Mark the class as scanned
classInfo.isScannedClass = true;
// Mark the class as non-external if it is an accepted class
classInfo.isExternalClass = isExternalClass;
// Remember which classpath element (zipfile / classpath root directory / module) the class was found in
classInfo.classpathElement = classpathElement;
// Remember which classloader is used to load the class
classInfo.classLoader = classpathElement.getClassLoader();
return classInfo;
}
// -------------------------------------------------------------------------------------------------------------
/** The class type to return. */
private enum ClassType {
/** Get all class types. */
ALL,
/** A standard class (not an interface or annotation). */
STANDARD_CLASS,
/**
* An interface (this is named "implemented interface" rather than just "interface" to distinguish it from
* an annotation.)
*/
IMPLEMENTED_INTERFACE,
/** An annotation. */
ANNOTATION,
/** An interface or annotation (used since you can actually implement an annotation). */
INTERFACE_OR_ANNOTATION,
/** An enum. */
ENUM,
/** A record type. */
RECORD
}
/**
* Filter classes according to scan spec and class type.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @param strictAccept
* If true, exclude class if it is external, if external classes are not enabled
* @param classTypes
* the class types
* @return the filtered classes.
*/
private static Set<ClassInfo> filterClassInfo(final Collection<ClassInfo> classes, final ScanSpec scanSpec,
final boolean strictAccept, final ClassType... classTypes) {
if (classes == null) {
return Collections.<ClassInfo> emptySet();
}
boolean includeAllTypes = classTypes.length == 0;
boolean includeStandardClasses = false;
boolean includeImplementedInterfaces = false;
boolean includeAnnotations = false;
boolean includeEnums = false;
boolean includeRecords = false;
for (final ClassType classType : classTypes) {
switch (classType) {
case ALL:
includeAllTypes = true;
break;
case STANDARD_CLASS:
includeStandardClasses = true;
break;
case IMPLEMENTED_INTERFACE:
includeImplementedInterfaces = true;
break;
case ANNOTATION:
includeAnnotations = true;
break;
case INTERFACE_OR_ANNOTATION:
includeImplementedInterfaces = includeAnnotations = true;
break;
case ENUM:
includeEnums = true;
break;
case RECORD:
includeRecords = true;
break;
default:
throw new IllegalArgumentException("Unknown ClassType: " + classType);
}
}
if (includeStandardClasses && includeImplementedInterfaces && includeAnnotations) {
includeAllTypes = true;
}
final Set<ClassInfo> classInfoSetFiltered = new LinkedHashSet<>(classes.size());
for (final ClassInfo classInfo : classes) {
// Check class type against requested type(s)
final boolean includeType = includeAllTypes //
|| includeStandardClasses && classInfo.isStandardClass() //
|| includeImplementedInterfaces && classInfo.isImplementedInterface() //
|| includeAnnotations && classInfo.isAnnotation() //
|| includeEnums && classInfo.isEnum() //
|| includeRecords && classInfo.isRecord();
// Return external (non-accepted) classes if viewing class hierarchy "upwards"
final boolean acceptClass = !classInfo.isExternalClass || scanSpec.enableExternalClasses
|| !strictAccept;
// If class is of correct type, and class is accepted, and class/package are not explicitly rejected
if (includeType && acceptClass && !scanSpec.classOrPackageIsRejected(classInfo.name)) {
// Class passed accept criteria
classInfoSetFiltered.add(classInfo);
}
}
return classInfoSetFiltered;
}
/**
* A set of classes that indirectly reachable through a directed path, for a given relationship type, and a set
* of classes that is directly related (only one relationship step away).
*/
static class ReachableAndDirectlyRelatedClasses {
/** The reachable classes. */
final Set<ClassInfo> reachableClasses;
/** The directly related classes. */
final Set<ClassInfo> directlyRelatedClasses;
/**
* Constructor.
*
* @param reachableClasses
* the reachable classes
* @param directlyRelatedClasses
* the directly related classes
*/
private ReachableAndDirectlyRelatedClasses(final Set<ClassInfo> reachableClasses,
final Set<ClassInfo> directlyRelatedClasses) {
this.reachableClasses = reachableClasses;
this.directlyRelatedClasses = directlyRelatedClasses;
}
}
/**
* Get the classes related to this one (the transitive closure) for the given relationship type, and those
* directly related.
*
* @param relType
* the relationship type
* @param strictAccept
* If true, exclude class if it is external, if external classes are not enabled
* @param classTypes
* the class types to accept
* @return the reachable and directly related classes
*/
private ReachableAndDirectlyRelatedClasses filterClassInfo(final RelType relType, final boolean strictAccept,
final ClassType... classTypes) {
Set<ClassInfo> directlyRelatedClasses = this.relatedClasses.get(relType);
if (directlyRelatedClasses == null) {
return NO_REACHABLE_CLASSES;
} else {
// Clone collection to prevent users modifying contents accidentally or intentionally
directlyRelatedClasses = new LinkedHashSet<>(directlyRelatedClasses);
}
final Set<ClassInfo> reachableClasses = new LinkedHashSet<>(directlyRelatedClasses);
if (relType == RelType.METHOD_ANNOTATIONS || relType == RelType.METHOD_PARAMETER_ANNOTATIONS
|| relType == RelType.FIELD_ANNOTATIONS) {
// For method and field annotations, need to change the RelType when finding meta-annotations
for (final ClassInfo annotation : directlyRelatedClasses) {
reachableClasses.addAll(
annotation.filterClassInfo(RelType.CLASS_ANNOTATIONS, strictAccept).reachableClasses);
}
} else if (relType == RelType.CLASSES_WITH_METHOD_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION
|| relType == RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION
|| relType == RelType.CLASSES_WITH_FIELD_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION) {
// If looking for meta-annotated methods or fields, need to find all meta-annotated annotations, then
// look for the methods or fields that they annotate
for (final ClassInfo subAnnotation : this.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, strictAccept,
ClassType.ANNOTATION).reachableClasses) {
final Set<ClassInfo> annotatedClasses = subAnnotation.relatedClasses.get(relType);
if (annotatedClasses != null) {
reachableClasses.addAll(annotatedClasses);
}
}
} else {
// For other relationship types, the reachable type stays the same over the transitive closure. Find the
// transitive closure, breaking cycles where necessary.
final LinkedList<ClassInfo> queue = new LinkedList<>(directlyRelatedClasses);
while (!queue.isEmpty()) {
final ClassInfo head = queue.removeFirst();
final Set<ClassInfo> headRelatedClasses = head.relatedClasses.get(relType);
if (headRelatedClasses != null) {
for (final ClassInfo directlyReachableFromHead : headRelatedClasses) {
// Don't get in cycle
if (reachableClasses.add(directlyReachableFromHead)) {
queue.add(directlyReachableFromHead);
}
}
}
}
}
if (reachableClasses.isEmpty()) {
return NO_REACHABLE_CLASSES;
}
if (relType == RelType.CLASS_ANNOTATIONS || relType == RelType.METHOD_ANNOTATIONS
|| relType == RelType.METHOD_PARAMETER_ANNOTATIONS || relType == RelType.FIELD_ANNOTATIONS) {
// Special case -- don't inherit java.lang.annotation.* meta-annotations as related meta-annotations
// (but still return them as direct meta-annotations on annotation classes).
Set<ClassInfo> reachableClassesToRemove = null;
for (final ClassInfo reachableClassInfo : reachableClasses) {
// Remove all java.lang.annotation annotations that are not directly related to this class
if (reachableClassInfo.getName().startsWith("java.lang.annotation.")
&& !directlyRelatedClasses.contains(reachableClassInfo)) {
if (reachableClassesToRemove == null) {
reachableClassesToRemove = new LinkedHashSet<>();
}
reachableClassesToRemove.add(reachableClassInfo);
}
}
if (reachableClassesToRemove != null) {
reachableClasses.removeAll(reachableClassesToRemove);
}
}
return new ReachableAndDirectlyRelatedClasses(
filterClassInfo(reachableClasses, scanResult.scanSpec, strictAccept, classTypes),
filterClassInfo(directlyRelatedClasses, scanResult.scanSpec, strictAccept, classTypes));
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get all classes found during the scan.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) {
return new ClassInfoList(
ClassInfo.filterClassInfo(classes, scanSpec, /* strictAccept = */ true, ClassType.ALL),
/* sortByName = */ true);
}
/**
* Get all {@link Enum} classes found during the scan.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all {@link Enum} classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllEnums(final Collection<ClassInfo> classes, final ScanSpec scanSpec) {
return new ClassInfoList(
ClassInfo.filterClassInfo(classes, scanSpec, /* strictAccept = */ true, ClassType.ENUM),
/* sortByName = */ true);
}
/**
* Get all {@code record} classes found during the scan.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all {@code record} classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllRecords(final Collection<ClassInfo> classes, final ScanSpec scanSpec) {