forked from classgraph/classgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFieldInfo.java
More file actions
608 lines (552 loc) · 22.4 KB
/
FieldInfo.java
File metadata and controls
608 lines (552 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
/*
* 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.lang.annotation.Repeatable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.github.classgraph.ClassInfo.RelType;
import io.github.classgraph.Classfile.TypeAnnotationDecorator;
import nonapi.io.github.classgraph.types.ParseException;
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 fields of a class encountered during a scan. All values are taken directly out of the
* classfile for the class.
*/
public class FieldInfo extends ScanResultObject implements Comparable<FieldInfo>, HasName {
/** The declaring class name. */
private String declaringClassName;
/** The name of the field. */
private String name;
/** The modifiers. */
private int modifiers;
/** The type signature string. */
private String typeSignatureStr;
/** The type descriptor string. */
private String typeDescriptorStr;
/** The parsed type signature. */
private transient TypeSignature typeSignature;
/** The parsed type descriptor. */
private transient TypeSignature typeDescriptor;
/** The constant initializer value for the field, if any. */
// This is transient because the constant initializer value is final, so the value doesn't need to be serialized
private ObjectTypedValueWrapper constantInitializerValue;
/** The annotation on the field, if any. */
AnnotationInfoList annotationInfo;
/** The type annotation decorators for the {@link TypeSignature} instance of this field. */
private List<TypeAnnotationDecorator> typeAnnotationDecorators;
// -------------------------------------------------------------------------------------------------------------
/** Default constructor for deserialization. */
FieldInfo() {
super();
}
/**
* Constructor.
*
* @param definingClassName
* The class the field is defined within.
* @param fieldName
* The name of the field.
* @param modifiers
* The field modifiers.
* @param typeDescriptorStr
* The field type descriptor.
* @param typeSignatureStr
* The field type signature.
* @param constantInitializerValue
* The static constant value the field is initialized to, if any.
* @param annotationInfo
* {@link AnnotationInfo} for any annotations on the field.
*/
FieldInfo(final String definingClassName, final String fieldName, final int modifiers,
final String typeDescriptorStr, final String typeSignatureStr, final Object constantInitializerValue,
final AnnotationInfoList annotationInfo, final List<TypeAnnotationDecorator> typeAnnotationDecorators) {
super();
if (fieldName == null) {
throw new IllegalArgumentException();
}
this.declaringClassName = definingClassName;
this.name = fieldName;
this.modifiers = modifiers;
this.typeDescriptorStr = typeDescriptorStr;
this.typeSignatureStr = typeSignatureStr;
this.constantInitializerValue = constantInitializerValue == null ? null
: new ObjectTypedValueWrapper(constantInitializerValue);
this.annotationInfo = annotationInfo == null || annotationInfo.isEmpty() ? null : annotationInfo;
this.typeAnnotationDecorators = typeAnnotationDecorators;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the name of the field.
*
* @return The name of the field.
*/
@Override
public String getName() {
return name;
}
/**
* Get the {@link ClassInfo} object for the class that declares this field.
*
* @return The {@link ClassInfo} object for the declaring class.
*
* @see #getClassName()
*/
@Override
public ClassInfo getClassInfo() {
return super.getClassInfo();
}
// -------------------------------------------------------------------------------------------------------------
/**
* Deprecated -- use {@link #getModifiersStr()} instead.
*
* @deprecated Use {@link #getModifiersStr()} instead.
* @return The field modifiers, as a string.
*/
@Deprecated
public String getModifierStr() {
return getModifiersStr();
}
/**
* Get the field modifiers as a string, e.g. "public static final". For the modifier bits, call getModifiers().
*
* @return The field modifiers, as a string.
*/
public String getModifiersStr() {
final StringBuilder buf = new StringBuilder();
TypeUtils.modifiersToString(modifiers, ModifierType.FIELD, /* ignored */ false, buf);
return buf.toString();
}
/**
* Returns true if this field is public.
*
* @return True if the field is public.
*/
public boolean isPublic() {
return Modifier.isPublic(modifiers);
}
/**
* Returns true if this field is static.
*
* @return True if the field is static.
*/
public boolean isStatic() {
return Modifier.isStatic(modifiers);
}
/**
* Returns true if this field is final.
*
* @return True if the field is final.
*/
public boolean isFinal() {
return Modifier.isFinal(modifiers);
}
/**
* Returns true if this field is a transient field.
*
* @return True if the field is transient.
*/
public boolean isTransient() {
return Modifier.isTransient(modifiers);
}
/**
* Returns the modifier bits for the field.
*
* @return The modifier bits.
*/
public int getModifiers() {
return modifiers;
}
/**
* Returns the parsed type descriptor for the field, which will not include type parameters. If you need generic
* type parameters, call {@link #getTypeSignature()} instead.
*
* @return The parsed type descriptor string for the field.
*/
public TypeSignature getTypeDescriptor() {
if (typeDescriptorStr == null) {
return null;
}
if (typeDescriptor == null) {
try {
typeDescriptor = TypeSignature.parse(typeDescriptorStr, declaringClassName);
typeDescriptor.setScanResult(scanResult);
if (typeAnnotationDecorators != null) {
for (final TypeAnnotationDecorator decorator : typeAnnotationDecorators) {
decorator.decorate(typeDescriptor);
}
}
} catch (final ParseException e) {
throw new IllegalArgumentException(e);
}
}
return typeDescriptor;
}
/**
* Returns the type descriptor string for the field, which will not include type parameters. If you need generic
* type parameters, call {@link #getTypeSignatureStr()} instead.
*
* @return The type descriptor string for the field.
*/
public String getTypeDescriptorStr() {
return typeDescriptorStr;
}
/**
* Returns the parsed type signature for the field, possibly including type parameters. If this returns null,
* indicating that no type signature information is available for this field, call {@link #getTypeDescriptor()}
* instead.
*
* @return The parsed type signature for the field, or null if not available.
* @throws IllegalArgumentException
* if the field type signature cannot be parsed (this should only be thrown in the case of classfile
* corruption, or a compiler bug that causes an invalid type signature to be written to the
* classfile).
*/
public TypeSignature getTypeSignature() {
if (typeSignatureStr == null) {
return null;
}
if (typeSignature == null) {
try {
typeSignature = TypeSignature.parse(typeSignatureStr, declaringClassName);
typeSignature.setScanResult(scanResult);
if (typeAnnotationDecorators != null) {
for (final TypeAnnotationDecorator decorator : typeAnnotationDecorators) {
decorator.decorate(typeSignature);
}
}
} catch (final ParseException e) {
throw new IllegalArgumentException(
"Invalid type signature for field " + getClassName() + "." + getName()
+ (getClassInfo() != null
? " in classpath element " + getClassInfo().getClasspathElementURI()
: "")
+ " : " + typeSignatureStr,
e);
}
}
return typeSignature;
}
/**
* Returns the type signature string for the field, possibly including type parameters. If this returns null,
* indicating that no type signature information is available for this field, call
* {@link #getTypeDescriptorStr()} instead.
*
* @return The type signature string for the field, or null if not available.
*/
public String getTypeSignatureStr() {
return typeSignatureStr;
}
/**
* Returns the type signature for the field, possibly including type parameters. If the type signature is null,
* indicating that no type signature information is available for this field, returns the type descriptor
* instead.
*
* @return The parsed type signature for the field, or if not available, the parsed type descriptor for the
* field.
*/
public TypeSignature getTypeSignatureOrTypeDescriptor() {
TypeSignature typeSig = null;
try {
typeSig = getTypeSignature();
if (typeSig != null) {
return typeSig;
}
} catch (final Exception e) {
// Ignore
}
return getTypeDescriptor();
}
/**
* Returns the type signature string for the field, possibly including type parameters. If the type signature
* string is null, indicating that no type signature information is available for this field, returns the type
* descriptor string instead.
*
* @return The type signature string for the field, or if not available, the type descriptor string for the
* method.
*/
public String getTypeSignatureOrTypeDescriptorStr() {
if (typeSignatureStr != null) {
return typeSignatureStr;
} else {
return typeDescriptorStr;
}
}
/**
* Returns the constant initializer value of a field. Requires
* {@link ClassGraph#enableStaticFinalFieldConstantInitializerValues()} to have been called. Will only return
* non-null for fields that have constant initializers, which is usually only fields of primitive type, or
* String constants. Also note that it is up to the compiler as to whether or not a constant-valued field is
* assigned as a constant in the field definition itself, or whether it is assigned manually in static or
* non-static class initializer blocks or the constructor -- so your mileage may vary in being able to extract
* constant initializer values.
*
* @return The initializer value, if this field has a constant initializer value, or null if none.
*/
public Object getConstantInitializerValue() {
if (!scanResult.scanSpec.enableStaticFinalFieldConstantInitializerValues) {
throw new IllegalArgumentException(
"Please call ClassGraph#enableStaticFinalFieldConstantInitializerValues() " + "before #scan()");
}
return constantInitializerValue == null ? null : constantInitializerValue.get();
}
/**
* Get a list of annotations on this field, along with any annotation parameter values, wrapped in
* {@link AnnotationInfo} objects.
*
* @return A list of annotations on this field, along with any annotation parameter values, wrapped in
* {@link AnnotationInfo} objects, or the empty list if none.
*/
public AnnotationInfoList getAnnotationInfo() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
return annotationInfo == null ? AnnotationInfoList.EMPTY_LIST
: AnnotationInfoList.getIndirectAnnotations(annotationInfo, /* annotatedClass = */ null);
}
/**
* Get a the named non-{@link Repeatable} annotation on this field, or null if the field does not have the named
* annotation. (Use {@link #getAnnotationInfoRepeatable(String)} for {@link Repeatable} annotations.)
*
* @param annotationName
* The annotation name.
* @return An {@link AnnotationInfo} object representing the named annotation on this field, or null if the
* field does not have the named annotation.
*/
public AnnotationInfo getAnnotationInfo(final String annotationName) {
return getAnnotationInfo().get(annotationName);
}
/**
* Get a the named {@link Repeatable} annotation on this field, or the empty list if the field does not have the
* named annotation.
*
* @param annotationName
* The annotation name.
* @return An {@link AnnotationInfoList} of all instances of the named annotation on this field, or the empty
* list if the field does not have the named annotation.
*/
public AnnotationInfoList getAnnotationInfoRepeatable(final String annotationName) {
return getAnnotationInfo().getRepeatable(annotationName);
}
/**
* Check if the field has a given named annotation.
*
* @param annotationName
* The name of an annotation.
* @return true if this field has the named annotation.
*/
public boolean hasAnnotation(final String annotationName) {
return getAnnotationInfo().containsName(annotationName);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Load the class this field is associated with, and get the {@link Field} reference for this field.
*
* @return The {@link Field} reference for this field.
* @throws IllegalArgumentException
* if the field does not exist.
*/
public Field loadClassAndGetField() throws IllegalArgumentException {
try {
return loadClass().getField(getName());
} catch (final NoSuchFieldException e1) {
try {
return loadClass().getDeclaredField(getName());
} catch (final NoSuchFieldException e2) {
throw new IllegalArgumentException("No such field: " + getClassName() + "." + getName());
}
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Handle {@link Repeatable} annotations.
*
* @param allRepeatableAnnotationNames
* the names of all repeatable annotations
*/
void handleRepeatableAnnotations(final Set<String> allRepeatableAnnotationNames) {
if (annotationInfo != null) {
annotationInfo.handleRepeatableAnnotations(allRepeatableAnnotationNames, getClassInfo(),
RelType.FIELD_ANNOTATIONS, RelType.CLASSES_WITH_FIELD_ANNOTATION,
RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the name of the class that declares this field.
*
* @return The name of the declaring class.
*
* @see #getClassInfo()
*/
@Override
public String getClassName() {
return declaringClassName;
}
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#setScanResult(io.github.classgraph.ScanResult)
*/
@Override
void setScanResult(final ScanResult scanResult) {
super.setScanResult(scanResult);
if (this.typeSignature != null) {
this.typeSignature.setScanResult(scanResult);
}
if (this.typeDescriptor != null) {
this.typeDescriptor.setScanResult(scanResult);
}
if (this.annotationInfo != null) {
for (final AnnotationInfo ai : this.annotationInfo) {
ai.setScanResult(scanResult);
}
}
}
/**
* Get {@link ClassInfo} objects for any classes referenced in the type descriptor or type signature.
*
* @param classNameToClassInfo
* the map from class name to {@link ClassInfo}.
* @param refdClassInfo
* the referenced class info
*/
@Override
protected void findReferencedClassInfo(final Map<String, ClassInfo> classNameToClassInfo,
final Set<ClassInfo> refdClassInfo, final LogNode log) {
try {
final TypeSignature fieldSig = getTypeSignature();
if (fieldSig != null) {
fieldSig.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log);
}
} catch (final IllegalArgumentException e) {
if (log != null) {
log.log("Illegal type signature for field " + getClassName() + "." + getName() + ": "
+ getTypeSignatureStr());
}
}
try {
final TypeSignature fieldDesc = getTypeDescriptor();
if (fieldDesc != null) {
fieldDesc.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log);
}
} catch (final IllegalArgumentException e) {
if (log != null) {
log.log("Illegal type descriptor for field " + getClassName() + "." + getName() + ": "
+ getTypeDescriptorStr());
}
}
if (annotationInfo != null) {
for (final AnnotationInfo ai : annotationInfo) {
ai.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log);
}
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Use class name and field name for equals().
*
* @param obj
* the object to compare to
* @return true if equal
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof FieldInfo)) {
return false;
}
final FieldInfo other = (FieldInfo) obj;
return declaringClassName.equals(other.declaringClassName) && name.equals(other.name);
}
/**
* Use hash code of class name and field name.
*
* @return the hashcode
*/
@Override
public int hashCode() {
return name.hashCode() + declaringClassName.hashCode() * 11;
}
/**
* Sort in order of class name then field name.
*
* @param other
* the other FieldInfo object to compare to.
* @return the result of comparison.
*/
@Override
public int compareTo(final FieldInfo other) {
final int diff = declaringClassName.compareTo(other.declaringClassName);
if (diff != 0) {
return diff;
}
return name.compareTo(other.name);
}
// -------------------------------------------------------------------------------------------------------------
@Override
protected void toString(final boolean useSimpleNames, final StringBuilder buf) {
if (annotationInfo != null) {
for (final AnnotationInfo annotation : annotationInfo) {
if (buf.length() > 0) {
buf.append(' ');
}
annotation.toString(useSimpleNames, buf);
}
}
if (modifiers != 0) {
if (buf.length() > 0) {
buf.append(' ');
}
TypeUtils.modifiersToString(modifiers, ModifierType.FIELD, /* ignored */ false, buf);
}
if (buf.length() > 0) {
buf.append(' ');
}
final TypeSignature typeSig = getTypeSignatureOrTypeDescriptor();
typeSig.toStringInternal(useSimpleNames, /* annotationsToExclude = */ annotationInfo, buf);
buf.append(' ');
buf.append(name);
if (constantInitializerValue != null) {
final Object val = constantInitializerValue.get();
buf.append(" = ");
if (val instanceof String) {
buf.append('"').append(((String) val).replace("\\", "\\\\").replace("\"", "\\\"")).append('"');
} else if (val instanceof Character) {
buf.append('\'').append(((Character) val).toString().replace("\\", "\\\\").replaceAll("'", "\\'"))
.append('\'');
} else {
buf.append(val == null ? "null" : val.toString());
}
}
}
}