Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/lang/Class.java
38829 views
1
/*
2
* Copyright (c) 1994, 2014, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.lang;
27
28
import java.lang.reflect.AnnotatedElement;
29
import java.lang.reflect.Array;
30
import java.lang.reflect.GenericArrayType;
31
import java.lang.reflect.GenericDeclaration;
32
import java.lang.reflect.Member;
33
import java.lang.reflect.Field;
34
import java.lang.reflect.Executable;
35
import java.lang.reflect.Method;
36
import java.lang.reflect.Constructor;
37
import java.lang.reflect.Modifier;
38
import java.lang.reflect.Type;
39
import java.lang.reflect.TypeVariable;
40
import java.lang.reflect.InvocationTargetException;
41
import java.lang.reflect.AnnotatedType;
42
import java.lang.ref.SoftReference;
43
import java.io.InputStream;
44
import java.io.ObjectStreamField;
45
import java.security.AccessController;
46
import java.security.PrivilegedAction;
47
import java.util.ArrayList;
48
import java.util.Arrays;
49
import java.util.Collection;
50
import java.util.HashSet;
51
import java.util.LinkedHashMap;
52
import java.util.List;
53
import java.util.Set;
54
import java.util.Map;
55
import java.util.HashMap;
56
import java.util.Objects;
57
import sun.misc.Unsafe;
58
import sun.reflect.CallerSensitive;
59
import sun.reflect.ConstantPool;
60
import sun.reflect.Reflection;
61
import sun.reflect.ReflectionFactory;
62
import sun.reflect.generics.factory.CoreReflectionFactory;
63
import sun.reflect.generics.factory.GenericsFactory;
64
import sun.reflect.generics.repository.ClassRepository;
65
import sun.reflect.generics.repository.MethodRepository;
66
import sun.reflect.generics.repository.ConstructorRepository;
67
import sun.reflect.generics.scope.ClassScope;
68
import sun.security.util.SecurityConstants;
69
import java.lang.annotation.Annotation;
70
import java.lang.reflect.Proxy;
71
import sun.reflect.annotation.*;
72
import sun.reflect.misc.ReflectUtil;
73
74
/**
75
* Instances of the class {@code Class} represent classes and
76
* interfaces in a running Java application. An enum is a kind of
77
* class and an annotation is a kind of interface. Every array also
78
* belongs to a class that is reflected as a {@code Class} object
79
* that is shared by all arrays with the same element type and number
80
* of dimensions. The primitive Java types ({@code boolean},
81
* {@code byte}, {@code char}, {@code short},
82
* {@code int}, {@code long}, {@code float}, and
83
* {@code double}), and the keyword {@code void} are also
84
* represented as {@code Class} objects.
85
*
86
* <p> {@code Class} has no public constructor. Instead {@code Class}
87
* objects are constructed automatically by the Java Virtual Machine as classes
88
* are loaded and by calls to the {@code defineClass} method in the class
89
* loader.
90
*
91
* <p> The following example uses a {@code Class} object to print the
92
* class name of an object:
93
*
94
* <blockquote><pre>
95
* void printClassName(Object obj) {
96
* System.out.println("The class of " + obj +
97
* " is " + obj.getClass().getName());
98
* }
99
* </pre></blockquote>
100
*
101
* <p> It is also possible to get the {@code Class} object for a named
102
* type (or for void) using a class literal. See Section 15.8.2 of
103
* <cite>The Java&trade; Language Specification</cite>.
104
* For example:
105
*
106
* <blockquote>
107
* {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
108
* </blockquote>
109
*
110
* @param <T> the type of the class modeled by this {@code Class}
111
* object. For example, the type of {@code String.class} is {@code
112
* Class<String>}. Use {@code Class<?>} if the class being modeled is
113
* unknown.
114
*
115
* @author unascribed
116
* @see java.lang.ClassLoader#defineClass(byte[], int, int)
117
* @since JDK1.0
118
*/
119
public final class Class<T> implements java.io.Serializable,
120
GenericDeclaration,
121
Type,
122
AnnotatedElement {
123
private static final int ANNOTATION= 0x00002000;
124
private static final int ENUM = 0x00004000;
125
private static final int SYNTHETIC = 0x00001000;
126
127
private static native void registerNatives();
128
static {
129
registerNatives();
130
}
131
132
/*
133
* Private constructor. Only the Java Virtual Machine creates Class objects.
134
* This constructor is not used and prevents the default constructor being
135
* generated.
136
*/
137
private Class(ClassLoader loader) {
138
// Initialize final field for classLoader. The initialization value of non-null
139
// prevents future JIT optimizations from assuming this final field is null.
140
classLoader = loader;
141
}
142
143
/**
144
* Converts the object to a string. The string representation is the
145
* string "class" or "interface", followed by a space, and then by the
146
* fully qualified name of the class in the format returned by
147
* {@code getName}. If this {@code Class} object represents a
148
* primitive type, this method returns the name of the primitive type. If
149
* this {@code Class} object represents void this method returns
150
* "void".
151
*
152
* @return a string representation of this class object.
153
*/
154
public String toString() {
155
return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
156
+ getName();
157
}
158
159
/**
160
* Returns a string describing this {@code Class}, including
161
* information about modifiers and type parameters.
162
*
163
* The string is formatted as a list of type modifiers, if any,
164
* followed by the kind of type (empty string for primitive types
165
* and {@code class}, {@code enum}, {@code interface}, or
166
* <code>&#64;</code>{@code interface}, as appropriate), followed
167
* by the type's name, followed by an angle-bracketed
168
* comma-separated list of the type's type parameters, if any.
169
*
170
* A space is used to separate modifiers from one another and to
171
* separate any modifiers from the kind of type. The modifiers
172
* occur in canonical order. If there are no type parameters, the
173
* type parameter list is elided.
174
*
175
* <p>Note that since information about the runtime representation
176
* of a type is being generated, modifiers not present on the
177
* originating source code or illegal on the originating source
178
* code may be present.
179
*
180
* @return a string describing this {@code Class}, including
181
* information about modifiers and type parameters
182
*
183
* @since 1.8
184
*/
185
public String toGenericString() {
186
if (isPrimitive()) {
187
return toString();
188
} else {
189
StringBuilder sb = new StringBuilder();
190
191
// Class modifiers are a superset of interface modifiers
192
int modifiers = getModifiers() & Modifier.classModifiers();
193
if (modifiers != 0) {
194
sb.append(Modifier.toString(modifiers));
195
sb.append(' ');
196
}
197
198
if (isAnnotation()) {
199
sb.append('@');
200
}
201
if (isInterface()) { // Note: all annotation types are interfaces
202
sb.append("interface");
203
} else {
204
if (isEnum())
205
sb.append("enum");
206
else
207
sb.append("class");
208
}
209
sb.append(' ');
210
sb.append(getName());
211
212
TypeVariable<?>[] typeparms = getTypeParameters();
213
if (typeparms.length > 0) {
214
boolean first = true;
215
sb.append('<');
216
for(TypeVariable<?> typeparm: typeparms) {
217
if (!first)
218
sb.append(',');
219
sb.append(typeparm.getTypeName());
220
first = false;
221
}
222
sb.append('>');
223
}
224
225
return sb.toString();
226
}
227
}
228
229
/**
230
* Returns the {@code Class} object associated with the class or
231
* interface with the given string name. Invoking this method is
232
* equivalent to:
233
*
234
* <blockquote>
235
* {@code Class.forName(className, true, currentLoader)}
236
* </blockquote>
237
*
238
* where {@code currentLoader} denotes the defining class loader of
239
* the current class.
240
*
241
* <p> For example, the following code fragment returns the
242
* runtime {@code Class} descriptor for the class named
243
* {@code java.lang.Thread}:
244
*
245
* <blockquote>
246
* {@code Class t = Class.forName("java.lang.Thread")}
247
* </blockquote>
248
* <p>
249
* A call to {@code forName("X")} causes the class named
250
* {@code X} to be initialized.
251
*
252
* @param className the fully qualified name of the desired class.
253
* @return the {@code Class} object for the class with the
254
* specified name.
255
* @exception LinkageError if the linkage fails
256
* @exception ExceptionInInitializerError if the initialization provoked
257
* by this method fails
258
* @exception ClassNotFoundException if the class cannot be located
259
*/
260
@CallerSensitive
261
public static Class<?> forName(String className)
262
throws ClassNotFoundException {
263
Class<?> caller = Reflection.getCallerClass();
264
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
265
}
266
267
268
/**
269
* Returns the {@code Class} object associated with the class or
270
* interface with the given string name, using the given class loader.
271
* Given the fully qualified name for a class or interface (in the same
272
* format returned by {@code getName}) this method attempts to
273
* locate, load, and link the class or interface. The specified class
274
* loader is used to load the class or interface. If the parameter
275
* {@code loader} is null, the class is loaded through the bootstrap
276
* class loader. The class is initialized only if the
277
* {@code initialize} parameter is {@code true} and if it has
278
* not been initialized earlier.
279
*
280
* <p> If {@code name} denotes a primitive type or void, an attempt
281
* will be made to locate a user-defined class in the unnamed package whose
282
* name is {@code name}. Therefore, this method cannot be used to
283
* obtain any of the {@code Class} objects representing primitive
284
* types or void.
285
*
286
* <p> If {@code name} denotes an array class, the component type of
287
* the array class is loaded but not initialized.
288
*
289
* <p> For example, in an instance method the expression:
290
*
291
* <blockquote>
292
* {@code Class.forName("Foo")}
293
* </blockquote>
294
*
295
* is equivalent to:
296
*
297
* <blockquote>
298
* {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
299
* </blockquote>
300
*
301
* Note that this method throws errors related to loading, linking or
302
* initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
303
* Java Language Specification</em>.
304
* Note that this method does not check whether the requested class
305
* is accessible to its caller.
306
*
307
* <p> If the {@code loader} is {@code null}, and a security
308
* manager is present, and the caller's class loader is not null, then this
309
* method calls the security manager's {@code checkPermission} method
310
* with a {@code RuntimePermission("getClassLoader")} permission to
311
* ensure it's ok to access the bootstrap class loader.
312
*
313
* @param name fully qualified name of the desired class
314
* @param initialize if {@code true} the class will be initialized.
315
* See Section 12.4 of <em>The Java Language Specification</em>.
316
* @param loader class loader from which the class must be loaded
317
* @return class object representing the desired class
318
*
319
* @exception LinkageError if the linkage fails
320
* @exception ExceptionInInitializerError if the initialization provoked
321
* by this method fails
322
* @exception ClassNotFoundException if the class cannot be located by
323
* the specified class loader
324
*
325
* @see java.lang.Class#forName(String)
326
* @see java.lang.ClassLoader
327
* @since 1.2
328
*/
329
@CallerSensitive
330
public static Class<?> forName(String name, boolean initialize,
331
ClassLoader loader)
332
throws ClassNotFoundException
333
{
334
Class<?> caller = null;
335
SecurityManager sm = System.getSecurityManager();
336
if (sm != null) {
337
// Reflective call to get caller class is only needed if a security manager
338
// is present. Avoid the overhead of making this call otherwise.
339
caller = Reflection.getCallerClass();
340
if (sun.misc.VM.isSystemDomainLoader(loader)) {
341
ClassLoader ccl = ClassLoader.getClassLoader(caller);
342
if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
343
sm.checkPermission(
344
SecurityConstants.GET_CLASSLOADER_PERMISSION);
345
}
346
}
347
}
348
return forName0(name, initialize, loader, caller);
349
}
350
351
/** Called after security check for system loader access checks have been made. */
352
private static native Class<?> forName0(String name, boolean initialize,
353
ClassLoader loader,
354
Class<?> caller)
355
throws ClassNotFoundException;
356
357
/**
358
* Creates a new instance of the class represented by this {@code Class}
359
* object. The class is instantiated as if by a {@code new}
360
* expression with an empty argument list. The class is initialized if it
361
* has not already been initialized.
362
*
363
* <p>Note that this method propagates any exception thrown by the
364
* nullary constructor, including a checked exception. Use of
365
* this method effectively bypasses the compile-time exception
366
* checking that would otherwise be performed by the compiler.
367
* The {@link
368
* java.lang.reflect.Constructor#newInstance(java.lang.Object...)
369
* Constructor.newInstance} method avoids this problem by wrapping
370
* any exception thrown by the constructor in a (checked) {@link
371
* java.lang.reflect.InvocationTargetException}.
372
*
373
* @return a newly allocated instance of the class represented by this
374
* object.
375
* @throws IllegalAccessException if the class or its nullary
376
* constructor is not accessible.
377
* @throws InstantiationException
378
* if this {@code Class} represents an abstract class,
379
* an interface, an array class, a primitive type, or void;
380
* or if the class has no nullary constructor;
381
* or if the instantiation fails for some other reason.
382
* @throws ExceptionInInitializerError if the initialization
383
* provoked by this method fails.
384
* @throws SecurityException
385
* If a security manager, <i>s</i>, is present and
386
* the caller's class loader is not the same as or an
387
* ancestor of the class loader for the current class and
388
* invocation of {@link SecurityManager#checkPackageAccess
389
* s.checkPackageAccess()} denies access to the package
390
* of this class.
391
*/
392
@CallerSensitive
393
public T newInstance()
394
throws InstantiationException, IllegalAccessException
395
{
396
if (System.getSecurityManager() != null) {
397
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
398
}
399
400
// NOTE: the following code may not be strictly correct under
401
// the current Java memory model.
402
403
// Constructor lookup
404
if (cachedConstructor == null) {
405
if (this == Class.class) {
406
throw new IllegalAccessException(
407
"Can not call newInstance() on the Class for java.lang.Class"
408
);
409
}
410
try {
411
Class<?>[] empty = {};
412
final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
413
// Disable accessibility checks on the constructor
414
// since we have to do the security check here anyway
415
// (the stack depth is wrong for the Constructor's
416
// security check to work)
417
java.security.AccessController.doPrivileged(
418
new java.security.PrivilegedAction<Void>() {
419
public Void run() {
420
c.setAccessible(true);
421
return null;
422
}
423
});
424
cachedConstructor = c;
425
} catch (NoSuchMethodException e) {
426
throw (InstantiationException)
427
new InstantiationException(getName()).initCause(e);
428
}
429
}
430
Constructor<T> tmpConstructor = cachedConstructor;
431
// Security check (same as in java.lang.reflect.Constructor)
432
int modifiers = tmpConstructor.getModifiers();
433
if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
434
Class<?> caller = Reflection.getCallerClass();
435
if (newInstanceCallerCache != caller) {
436
Reflection.ensureMemberAccess(caller, this, null, modifiers);
437
newInstanceCallerCache = caller;
438
}
439
}
440
// Run constructor
441
try {
442
return tmpConstructor.newInstance((Object[])null);
443
} catch (InvocationTargetException e) {
444
Unsafe.getUnsafe().throwException(e.getTargetException());
445
// Not reached
446
return null;
447
}
448
}
449
private volatile transient Constructor<T> cachedConstructor;
450
private volatile transient Class<?> newInstanceCallerCache;
451
452
453
/**
454
* Determines if the specified {@code Object} is assignment-compatible
455
* with the object represented by this {@code Class}. This method is
456
* the dynamic equivalent of the Java language {@code instanceof}
457
* operator. The method returns {@code true} if the specified
458
* {@code Object} argument is non-null and can be cast to the
459
* reference type represented by this {@code Class} object without
460
* raising a {@code ClassCastException.} It returns {@code false}
461
* otherwise.
462
*
463
* <p> Specifically, if this {@code Class} object represents a
464
* declared class, this method returns {@code true} if the specified
465
* {@code Object} argument is an instance of the represented class (or
466
* of any of its subclasses); it returns {@code false} otherwise. If
467
* this {@code Class} object represents an array class, this method
468
* returns {@code true} if the specified {@code Object} argument
469
* can be converted to an object of the array class by an identity
470
* conversion or by a widening reference conversion; it returns
471
* {@code false} otherwise. If this {@code Class} object
472
* represents an interface, this method returns {@code true} if the
473
* class or any superclass of the specified {@code Object} argument
474
* implements this interface; it returns {@code false} otherwise. If
475
* this {@code Class} object represents a primitive type, this method
476
* returns {@code false}.
477
*
478
* @param obj the object to check
479
* @return true if {@code obj} is an instance of this class
480
*
481
* @since JDK1.1
482
*/
483
public native boolean isInstance(Object obj);
484
485
486
/**
487
* Determines if the class or interface represented by this
488
* {@code Class} object is either the same as, or is a superclass or
489
* superinterface of, the class or interface represented by the specified
490
* {@code Class} parameter. It returns {@code true} if so;
491
* otherwise it returns {@code false}. If this {@code Class}
492
* object represents a primitive type, this method returns
493
* {@code true} if the specified {@code Class} parameter is
494
* exactly this {@code Class} object; otherwise it returns
495
* {@code false}.
496
*
497
* <p> Specifically, this method tests whether the type represented by the
498
* specified {@code Class} parameter can be converted to the type
499
* represented by this {@code Class} object via an identity conversion
500
* or via a widening reference conversion. See <em>The Java Language
501
* Specification</em>, sections 5.1.1 and 5.1.4 , for details.
502
*
503
* @param cls the {@code Class} object to be checked
504
* @return the {@code boolean} value indicating whether objects of the
505
* type {@code cls} can be assigned to objects of this class
506
* @exception NullPointerException if the specified Class parameter is
507
* null.
508
* @since JDK1.1
509
*/
510
public native boolean isAssignableFrom(Class<?> cls);
511
512
513
/**
514
* Determines if the specified {@code Class} object represents an
515
* interface type.
516
*
517
* @return {@code true} if this object represents an interface;
518
* {@code false} otherwise.
519
*/
520
public native boolean isInterface();
521
522
523
/**
524
* Determines if this {@code Class} object represents an array class.
525
*
526
* @return {@code true} if this object represents an array class;
527
* {@code false} otherwise.
528
* @since JDK1.1
529
*/
530
public native boolean isArray();
531
532
533
/**
534
* Determines if the specified {@code Class} object represents a
535
* primitive type.
536
*
537
* <p> There are nine predefined {@code Class} objects to represent
538
* the eight primitive types and void. These are created by the Java
539
* Virtual Machine, and have the same names as the primitive types that
540
* they represent, namely {@code boolean}, {@code byte},
541
* {@code char}, {@code short}, {@code int},
542
* {@code long}, {@code float}, and {@code double}.
543
*
544
* <p> These objects may only be accessed via the following public static
545
* final variables, and are the only {@code Class} objects for which
546
* this method returns {@code true}.
547
*
548
* @return true if and only if this class represents a primitive type
549
*
550
* @see java.lang.Boolean#TYPE
551
* @see java.lang.Character#TYPE
552
* @see java.lang.Byte#TYPE
553
* @see java.lang.Short#TYPE
554
* @see java.lang.Integer#TYPE
555
* @see java.lang.Long#TYPE
556
* @see java.lang.Float#TYPE
557
* @see java.lang.Double#TYPE
558
* @see java.lang.Void#TYPE
559
* @since JDK1.1
560
*/
561
public native boolean isPrimitive();
562
563
/**
564
* Returns true if this {@code Class} object represents an annotation
565
* type. Note that if this method returns true, {@link #isInterface()}
566
* would also return true, as all annotation types are also interfaces.
567
*
568
* @return {@code true} if this class object represents an annotation
569
* type; {@code false} otherwise
570
* @since 1.5
571
*/
572
public boolean isAnnotation() {
573
return (getModifiers() & ANNOTATION) != 0;
574
}
575
576
/**
577
* Returns {@code true} if this class is a synthetic class;
578
* returns {@code false} otherwise.
579
* @return {@code true} if and only if this class is a synthetic class as
580
* defined by the Java Language Specification.
581
* @jls 13.1 The Form of a Binary
582
* @since 1.5
583
*/
584
public boolean isSynthetic() {
585
return (getModifiers() & SYNTHETIC) != 0;
586
}
587
588
/**
589
* Returns the name of the entity (class, interface, array class,
590
* primitive type, or void) represented by this {@code Class} object,
591
* as a {@code String}.
592
*
593
* <p> If this class object represents a reference type that is not an
594
* array type then the binary name of the class is returned, as specified
595
* by
596
* <cite>The Java&trade; Language Specification</cite>.
597
*
598
* <p> If this class object represents a primitive type or void, then the
599
* name returned is a {@code String} equal to the Java language
600
* keyword corresponding to the primitive type or void.
601
*
602
* <p> If this class object represents a class of arrays, then the internal
603
* form of the name consists of the name of the element type preceded by
604
* one or more '{@code [}' characters representing the depth of the array
605
* nesting. The encoding of element type names is as follows:
606
*
607
* <blockquote><table summary="Element types and encodings">
608
* <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
609
* <tr><td> boolean <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
610
* <tr><td> byte <td> &nbsp;&nbsp;&nbsp; <td align=center> B
611
* <tr><td> char <td> &nbsp;&nbsp;&nbsp; <td align=center> C
612
* <tr><td> class or interface
613
* <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
614
* <tr><td> double <td> &nbsp;&nbsp;&nbsp; <td align=center> D
615
* <tr><td> float <td> &nbsp;&nbsp;&nbsp; <td align=center> F
616
* <tr><td> int <td> &nbsp;&nbsp;&nbsp; <td align=center> I
617
* <tr><td> long <td> &nbsp;&nbsp;&nbsp; <td align=center> J
618
* <tr><td> short <td> &nbsp;&nbsp;&nbsp; <td align=center> S
619
* </table></blockquote>
620
*
621
* <p> The class or interface name <i>classname</i> is the binary name of
622
* the class specified above.
623
*
624
* <p> Examples:
625
* <blockquote><pre>
626
* String.class.getName()
627
* returns "java.lang.String"
628
* byte.class.getName()
629
* returns "byte"
630
* (new Object[3]).getClass().getName()
631
* returns "[Ljava.lang.Object;"
632
* (new int[3][4][5][6][7][8][9]).getClass().getName()
633
* returns "[[[[[[[I"
634
* </pre></blockquote>
635
*
636
* @return the name of the class or interface
637
* represented by this object.
638
*/
639
public String getName() {
640
String name = this.name;
641
if (name == null)
642
this.name = name = getName0();
643
return name;
644
}
645
646
// cache the name to reduce the number of calls into the VM
647
private transient String name;
648
private native String getName0();
649
650
/**
651
* Returns the class loader for the class. Some implementations may use
652
* null to represent the bootstrap class loader. This method will return
653
* null in such implementations if this class was loaded by the bootstrap
654
* class loader.
655
*
656
* <p> If a security manager is present, and the caller's class loader is
657
* not null and the caller's class loader is not the same as or an ancestor of
658
* the class loader for the class whose class loader is requested, then
659
* this method calls the security manager's {@code checkPermission}
660
* method with a {@code RuntimePermission("getClassLoader")}
661
* permission to ensure it's ok to access the class loader for the class.
662
*
663
* <p>If this object
664
* represents a primitive type or void, null is returned.
665
*
666
* @return the class loader that loaded the class or interface
667
* represented by this object.
668
* @throws SecurityException
669
* if a security manager exists and its
670
* {@code checkPermission} method denies
671
* access to the class loader for the class.
672
* @see java.lang.ClassLoader
673
* @see SecurityManager#checkPermission
674
* @see java.lang.RuntimePermission
675
*/
676
@CallerSensitive
677
public ClassLoader getClassLoader() {
678
ClassLoader cl = getClassLoader0();
679
if (cl == null)
680
return null;
681
SecurityManager sm = System.getSecurityManager();
682
if (sm != null) {
683
ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
684
}
685
return cl;
686
}
687
688
// Package-private to allow ClassLoader access
689
ClassLoader getClassLoader0() { return classLoader; }
690
691
// Initialized in JVM not by private constructor
692
// This field is filtered from reflection access, i.e. getDeclaredField
693
// will throw NoSuchFieldException
694
private final ClassLoader classLoader;
695
696
/**
697
* Returns an array of {@code TypeVariable} objects that represent the
698
* type variables declared by the generic declaration represented by this
699
* {@code GenericDeclaration} object, in declaration order. Returns an
700
* array of length 0 if the underlying generic declaration declares no type
701
* variables.
702
*
703
* @return an array of {@code TypeVariable} objects that represent
704
* the type variables declared by this generic declaration
705
* @throws java.lang.reflect.GenericSignatureFormatError if the generic
706
* signature of this generic declaration does not conform to
707
* the format specified in
708
* <cite>The Java&trade; Virtual Machine Specification</cite>
709
* @since 1.5
710
*/
711
@SuppressWarnings("unchecked")
712
public TypeVariable<Class<T>>[] getTypeParameters() {
713
ClassRepository info = getGenericInfo();
714
if (info != null)
715
return (TypeVariable<Class<T>>[])info.getTypeParameters();
716
else
717
return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
718
}
719
720
721
/**
722
* Returns the {@code Class} representing the superclass of the entity
723
* (class, interface, primitive type or void) represented by this
724
* {@code Class}. If this {@code Class} represents either the
725
* {@code Object} class, an interface, a primitive type, or void, then
726
* null is returned. If this object represents an array class then the
727
* {@code Class} object representing the {@code Object} class is
728
* returned.
729
*
730
* @return the superclass of the class represented by this object.
731
*/
732
public native Class<? super T> getSuperclass();
733
734
735
/**
736
* Returns the {@code Type} representing the direct superclass of
737
* the entity (class, interface, primitive type or void) represented by
738
* this {@code Class}.
739
*
740
* <p>If the superclass is a parameterized type, the {@code Type}
741
* object returned must accurately reflect the actual type
742
* parameters used in the source code. The parameterized type
743
* representing the superclass is created if it had not been
744
* created before. See the declaration of {@link
745
* java.lang.reflect.ParameterizedType ParameterizedType} for the
746
* semantics of the creation process for parameterized types. If
747
* this {@code Class} represents either the {@code Object}
748
* class, an interface, a primitive type, or void, then null is
749
* returned. If this object represents an array class then the
750
* {@code Class} object representing the {@code Object} class is
751
* returned.
752
*
753
* @throws java.lang.reflect.GenericSignatureFormatError if the generic
754
* class signature does not conform to the format specified in
755
* <cite>The Java&trade; Virtual Machine Specification</cite>
756
* @throws TypeNotPresentException if the generic superclass
757
* refers to a non-existent type declaration
758
* @throws java.lang.reflect.MalformedParameterizedTypeException if the
759
* generic superclass refers to a parameterized type that cannot be
760
* instantiated for any reason
761
* @return the superclass of the class represented by this object
762
* @since 1.5
763
*/
764
public Type getGenericSuperclass() {
765
ClassRepository info = getGenericInfo();
766
if (info == null) {
767
return getSuperclass();
768
}
769
770
// Historical irregularity:
771
// Generic signature marks interfaces with superclass = Object
772
// but this API returns null for interfaces
773
if (isInterface()) {
774
return null;
775
}
776
777
return info.getSuperclass();
778
}
779
780
/**
781
* Gets the package for this class. The class loader of this class is used
782
* to find the package. If the class was loaded by the bootstrap class
783
* loader the set of packages loaded from CLASSPATH is searched to find the
784
* package of the class. Null is returned if no package object was created
785
* by the class loader of this class.
786
*
787
* <p> Packages have attributes for versions and specifications only if the
788
* information was defined in the manifests that accompany the classes, and
789
* if the class loader created the package instance with the attributes
790
* from the manifest.
791
*
792
* @return the package of the class, or null if no package
793
* information is available from the archive or codebase.
794
*/
795
public Package getPackage() {
796
return Package.getPackage(this);
797
}
798
799
800
/**
801
* Determines the interfaces implemented by the class or interface
802
* represented by this object.
803
*
804
* <p> If this object represents a class, the return value is an array
805
* containing objects representing all interfaces implemented by the
806
* class. The order of the interface objects in the array corresponds to
807
* the order of the interface names in the {@code implements} clause
808
* of the declaration of the class represented by this object. For
809
* example, given the declaration:
810
* <blockquote>
811
* {@code class Shimmer implements FloorWax, DessertTopping { ... }}
812
* </blockquote>
813
* suppose the value of {@code s} is an instance of
814
* {@code Shimmer}; the value of the expression:
815
* <blockquote>
816
* {@code s.getClass().getInterfaces()[0]}
817
* </blockquote>
818
* is the {@code Class} object that represents interface
819
* {@code FloorWax}; and the value of:
820
* <blockquote>
821
* {@code s.getClass().getInterfaces()[1]}
822
* </blockquote>
823
* is the {@code Class} object that represents interface
824
* {@code DessertTopping}.
825
*
826
* <p> If this object represents an interface, the array contains objects
827
* representing all interfaces extended by the interface. The order of the
828
* interface objects in the array corresponds to the order of the interface
829
* names in the {@code extends} clause of the declaration of the
830
* interface represented by this object.
831
*
832
* <p> If this object represents a class or interface that implements no
833
* interfaces, the method returns an array of length 0.
834
*
835
* <p> If this object represents a primitive type or void, the method
836
* returns an array of length 0.
837
*
838
* <p> If this {@code Class} object represents an array type, the
839
* interfaces {@code Cloneable} and {@code java.io.Serializable} are
840
* returned in that order.
841
*
842
* @return an array of interfaces implemented by this class.
843
*/
844
public Class<?>[] getInterfaces() {
845
ReflectionData<T> rd = reflectionData();
846
if (rd == null) {
847
// no cloning required
848
return getInterfaces0();
849
} else {
850
Class<?>[] interfaces = rd.interfaces;
851
if (interfaces == null) {
852
interfaces = getInterfaces0();
853
rd.interfaces = interfaces;
854
}
855
// defensively copy before handing over to user code
856
return interfaces.clone();
857
}
858
}
859
860
private native Class<?>[] getInterfaces0();
861
862
/**
863
* Returns the {@code Type}s representing the interfaces
864
* directly implemented by the class or interface represented by
865
* this object.
866
*
867
* <p>If a superinterface is a parameterized type, the
868
* {@code Type} object returned for it must accurately reflect
869
* the actual type parameters used in the source code. The
870
* parameterized type representing each superinterface is created
871
* if it had not been created before. See the declaration of
872
* {@link java.lang.reflect.ParameterizedType ParameterizedType}
873
* for the semantics of the creation process for parameterized
874
* types.
875
*
876
* <p> If this object represents a class, the return value is an
877
* array containing objects representing all interfaces
878
* implemented by the class. The order of the interface objects in
879
* the array corresponds to the order of the interface names in
880
* the {@code implements} clause of the declaration of the class
881
* represented by this object. In the case of an array class, the
882
* interfaces {@code Cloneable} and {@code Serializable} are
883
* returned in that order.
884
*
885
* <p>If this object represents an interface, the array contains
886
* objects representing all interfaces directly extended by the
887
* interface. The order of the interface objects in the array
888
* corresponds to the order of the interface names in the
889
* {@code extends} clause of the declaration of the interface
890
* represented by this object.
891
*
892
* <p>If this object represents a class or interface that
893
* implements no interfaces, the method returns an array of length
894
* 0.
895
*
896
* <p>If this object represents a primitive type or void, the
897
* method returns an array of length 0.
898
*
899
* @throws java.lang.reflect.GenericSignatureFormatError
900
* if the generic class signature does not conform to the format
901
* specified in
902
* <cite>The Java&trade; Virtual Machine Specification</cite>
903
* @throws TypeNotPresentException if any of the generic
904
* superinterfaces refers to a non-existent type declaration
905
* @throws java.lang.reflect.MalformedParameterizedTypeException
906
* if any of the generic superinterfaces refer to a parameterized
907
* type that cannot be instantiated for any reason
908
* @return an array of interfaces implemented by this class
909
* @since 1.5
910
*/
911
public Type[] getGenericInterfaces() {
912
ClassRepository info = getGenericInfo();
913
return (info == null) ? getInterfaces() : info.getSuperInterfaces();
914
}
915
916
917
/**
918
* Returns the {@code Class} representing the component type of an
919
* array. If this class does not represent an array class this method
920
* returns null.
921
*
922
* @return the {@code Class} representing the component type of this
923
* class if this class is an array
924
* @see java.lang.reflect.Array
925
* @since JDK1.1
926
*/
927
public native Class<?> getComponentType();
928
929
930
/**
931
* Returns the Java language modifiers for this class or interface, encoded
932
* in an integer. The modifiers consist of the Java Virtual Machine's
933
* constants for {@code public}, {@code protected},
934
* {@code private}, {@code final}, {@code static},
935
* {@code abstract} and {@code interface}; they should be decoded
936
* using the methods of class {@code Modifier}.
937
*
938
* <p> If the underlying class is an array class, then its
939
* {@code public}, {@code private} and {@code protected}
940
* modifiers are the same as those of its component type. If this
941
* {@code Class} represents a primitive type or void, its
942
* {@code public} modifier is always {@code true}, and its
943
* {@code protected} and {@code private} modifiers are always
944
* {@code false}. If this object represents an array class, a
945
* primitive type or void, then its {@code final} modifier is always
946
* {@code true} and its interface modifier is always
947
* {@code false}. The values of its other modifiers are not determined
948
* by this specification.
949
*
950
* <p> The modifier encodings are defined in <em>The Java Virtual Machine
951
* Specification</em>, table 4.1.
952
*
953
* @return the {@code int} representing the modifiers for this class
954
* @see java.lang.reflect.Modifier
955
* @since JDK1.1
956
*/
957
public native int getModifiers();
958
959
960
/**
961
* Gets the signers of this class.
962
*
963
* @return the signers of this class, or null if there are no signers. In
964
* particular, this method returns null if this object represents
965
* a primitive type or void.
966
* @since JDK1.1
967
*/
968
public native Object[] getSigners();
969
970
971
/**
972
* Set the signers of this class.
973
*/
974
native void setSigners(Object[] signers);
975
976
977
/**
978
* If this {@code Class} object represents a local or anonymous
979
* class within a method, returns a {@link
980
* java.lang.reflect.Method Method} object representing the
981
* immediately enclosing method of the underlying class. Returns
982
* {@code null} otherwise.
983
*
984
* In particular, this method returns {@code null} if the underlying
985
* class is a local or anonymous class immediately enclosed by a type
986
* declaration, instance initializer or static initializer.
987
*
988
* @return the immediately enclosing method of the underlying class, if
989
* that class is a local or anonymous class; otherwise {@code null}.
990
*
991
* @throws SecurityException
992
* If a security manager, <i>s</i>, is present and any of the
993
* following conditions is met:
994
*
995
* <ul>
996
*
997
* <li> the caller's class loader is not the same as the
998
* class loader of the enclosing class and invocation of
999
* {@link SecurityManager#checkPermission
1000
* s.checkPermission} method with
1001
* {@code RuntimePermission("accessDeclaredMembers")}
1002
* denies access to the methods within the enclosing class
1003
*
1004
* <li> the caller's class loader is not the same as or an
1005
* ancestor of the class loader for the enclosing class and
1006
* invocation of {@link SecurityManager#checkPackageAccess
1007
* s.checkPackageAccess()} denies access to the package
1008
* of the enclosing class
1009
*
1010
* </ul>
1011
* @since 1.5
1012
*/
1013
@CallerSensitive
1014
public Method getEnclosingMethod() throws SecurityException {
1015
EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1016
1017
if (enclosingInfo == null)
1018
return null;
1019
else {
1020
if (!enclosingInfo.isMethod())
1021
return null;
1022
1023
MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
1024
getFactory());
1025
Class<?> returnType = toClass(typeInfo.getReturnType());
1026
Type [] parameterTypes = typeInfo.getParameterTypes();
1027
Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1028
1029
// Convert Types to Classes; returned types *should*
1030
// be class objects since the methodDescriptor's used
1031
// don't have generics information
1032
for(int i = 0; i < parameterClasses.length; i++)
1033
parameterClasses[i] = toClass(parameterTypes[i]);
1034
1035
// Perform access check
1036
Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1037
enclosingCandidate.checkMemberAccess(Member.DECLARED,
1038
Reflection.getCallerClass(), true);
1039
/*
1040
* Loop over all declared methods; match method name,
1041
* number of and type of parameters, *and* return
1042
* type. Matching return type is also necessary
1043
* because of covariant returns, etc.
1044
*/
1045
for(Method m: enclosingCandidate.getDeclaredMethods()) {
1046
if (m.getName().equals(enclosingInfo.getName()) ) {
1047
Class<?>[] candidateParamClasses = m.getParameterTypes();
1048
if (candidateParamClasses.length == parameterClasses.length) {
1049
boolean matches = true;
1050
for(int i = 0; i < candidateParamClasses.length; i++) {
1051
if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1052
matches = false;
1053
break;
1054
}
1055
}
1056
1057
if (matches) { // finally, check return type
1058
if (m.getReturnType().equals(returnType) )
1059
return m;
1060
}
1061
}
1062
}
1063
}
1064
1065
throw new InternalError("Enclosing method not found");
1066
}
1067
}
1068
1069
private native Object[] getEnclosingMethod0();
1070
1071
private EnclosingMethodInfo getEnclosingMethodInfo() {
1072
Object[] enclosingInfo = getEnclosingMethod0();
1073
if (enclosingInfo == null)
1074
return null;
1075
else {
1076
return new EnclosingMethodInfo(enclosingInfo);
1077
}
1078
}
1079
1080
private final static class EnclosingMethodInfo {
1081
private Class<?> enclosingClass;
1082
private String name;
1083
private String descriptor;
1084
1085
private EnclosingMethodInfo(Object[] enclosingInfo) {
1086
if (enclosingInfo.length != 3)
1087
throw new InternalError("Malformed enclosing method information");
1088
try {
1089
// The array is expected to have three elements:
1090
1091
// the immediately enclosing class
1092
enclosingClass = (Class<?>) enclosingInfo[0];
1093
assert(enclosingClass != null);
1094
1095
// the immediately enclosing method or constructor's
1096
// name (can be null).
1097
name = (String) enclosingInfo[1];
1098
1099
// the immediately enclosing method or constructor's
1100
// descriptor (null iff name is).
1101
descriptor = (String) enclosingInfo[2];
1102
assert((name != null && descriptor != null) || name == descriptor);
1103
} catch (ClassCastException cce) {
1104
throw new InternalError("Invalid type in enclosing method information", cce);
1105
}
1106
}
1107
1108
boolean isPartial() {
1109
return enclosingClass == null || name == null || descriptor == null;
1110
}
1111
1112
boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
1113
1114
boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
1115
1116
Class<?> getEnclosingClass() { return enclosingClass; }
1117
1118
String getName() { return name; }
1119
1120
String getDescriptor() { return descriptor; }
1121
1122
}
1123
1124
private static Class<?> toClass(Type o) {
1125
if (o instanceof GenericArrayType)
1126
return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1127
0)
1128
.getClass();
1129
return (Class<?>)o;
1130
}
1131
1132
/**
1133
* If this {@code Class} object represents a local or anonymous
1134
* class within a constructor, returns a {@link
1135
* java.lang.reflect.Constructor Constructor} object representing
1136
* the immediately enclosing constructor of the underlying
1137
* class. Returns {@code null} otherwise. In particular, this
1138
* method returns {@code null} if the underlying class is a local
1139
* or anonymous class immediately enclosed by a type declaration,
1140
* instance initializer or static initializer.
1141
*
1142
* @return the immediately enclosing constructor of the underlying class, if
1143
* that class is a local or anonymous class; otherwise {@code null}.
1144
* @throws SecurityException
1145
* If a security manager, <i>s</i>, is present and any of the
1146
* following conditions is met:
1147
*
1148
* <ul>
1149
*
1150
* <li> the caller's class loader is not the same as the
1151
* class loader of the enclosing class and invocation of
1152
* {@link SecurityManager#checkPermission
1153
* s.checkPermission} method with
1154
* {@code RuntimePermission("accessDeclaredMembers")}
1155
* denies access to the constructors within the enclosing class
1156
*
1157
* <li> the caller's class loader is not the same as or an
1158
* ancestor of the class loader for the enclosing class and
1159
* invocation of {@link SecurityManager#checkPackageAccess
1160
* s.checkPackageAccess()} denies access to the package
1161
* of the enclosing class
1162
*
1163
* </ul>
1164
* @since 1.5
1165
*/
1166
@CallerSensitive
1167
public Constructor<?> getEnclosingConstructor() throws SecurityException {
1168
EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1169
1170
if (enclosingInfo == null)
1171
return null;
1172
else {
1173
if (!enclosingInfo.isConstructor())
1174
return null;
1175
1176
ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1177
getFactory());
1178
Type [] parameterTypes = typeInfo.getParameterTypes();
1179
Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1180
1181
// Convert Types to Classes; returned types *should*
1182
// be class objects since the methodDescriptor's used
1183
// don't have generics information
1184
for(int i = 0; i < parameterClasses.length; i++)
1185
parameterClasses[i] = toClass(parameterTypes[i]);
1186
1187
// Perform access check
1188
Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1189
enclosingCandidate.checkMemberAccess(Member.DECLARED,
1190
Reflection.getCallerClass(), true);
1191
/*
1192
* Loop over all declared constructors; match number
1193
* of and type of parameters.
1194
*/
1195
for(Constructor<?> c: enclosingCandidate.getDeclaredConstructors()) {
1196
Class<?>[] candidateParamClasses = c.getParameterTypes();
1197
if (candidateParamClasses.length == parameterClasses.length) {
1198
boolean matches = true;
1199
for(int i = 0; i < candidateParamClasses.length; i++) {
1200
if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1201
matches = false;
1202
break;
1203
}
1204
}
1205
1206
if (matches)
1207
return c;
1208
}
1209
}
1210
1211
throw new InternalError("Enclosing constructor not found");
1212
}
1213
}
1214
1215
1216
/**
1217
* If the class or interface represented by this {@code Class} object
1218
* is a member of another class, returns the {@code Class} object
1219
* representing the class in which it was declared. This method returns
1220
* null if this class or interface is not a member of any other class. If
1221
* this {@code Class} object represents an array class, a primitive
1222
* type, or void,then this method returns null.
1223
*
1224
* @return the declaring class for this class
1225
* @throws SecurityException
1226
* If a security manager, <i>s</i>, is present and the caller's
1227
* class loader is not the same as or an ancestor of the class
1228
* loader for the declaring class and invocation of {@link
1229
* SecurityManager#checkPackageAccess s.checkPackageAccess()}
1230
* denies access to the package of the declaring class
1231
* @since JDK1.1
1232
*/
1233
@CallerSensitive
1234
public Class<?> getDeclaringClass() throws SecurityException {
1235
final Class<?> candidate = getDeclaringClass0();
1236
1237
if (candidate != null)
1238
candidate.checkPackageAccess(
1239
ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1240
return candidate;
1241
}
1242
1243
private native Class<?> getDeclaringClass0();
1244
1245
1246
/**
1247
* Returns the immediately enclosing class of the underlying
1248
* class. If the underlying class is a top level class this
1249
* method returns {@code null}.
1250
* @return the immediately enclosing class of the underlying class
1251
* @exception SecurityException
1252
* If a security manager, <i>s</i>, is present and the caller's
1253
* class loader is not the same as or an ancestor of the class
1254
* loader for the enclosing class and invocation of {@link
1255
* SecurityManager#checkPackageAccess s.checkPackageAccess()}
1256
* denies access to the package of the enclosing class
1257
* @since 1.5
1258
*/
1259
@CallerSensitive
1260
public Class<?> getEnclosingClass() throws SecurityException {
1261
// There are five kinds of classes (or interfaces):
1262
// a) Top level classes
1263
// b) Nested classes (static member classes)
1264
// c) Inner classes (non-static member classes)
1265
// d) Local classes (named classes declared within a method)
1266
// e) Anonymous classes
1267
1268
1269
// JVM Spec 4.8.6: A class must have an EnclosingMethod
1270
// attribute if and only if it is a local class or an
1271
// anonymous class.
1272
EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1273
Class<?> enclosingCandidate;
1274
1275
if (enclosingInfo == null) {
1276
// This is a top level or a nested class or an inner class (a, b, or c)
1277
enclosingCandidate = getDeclaringClass();
1278
} else {
1279
Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1280
// This is a local class or an anonymous class (d or e)
1281
if (enclosingClass == this || enclosingClass == null)
1282
throw new InternalError("Malformed enclosing method information");
1283
else
1284
enclosingCandidate = enclosingClass;
1285
}
1286
1287
if (enclosingCandidate != null)
1288
enclosingCandidate.checkPackageAccess(
1289
ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1290
return enclosingCandidate;
1291
}
1292
1293
/**
1294
* Returns the simple name of the underlying class as given in the
1295
* source code. Returns an empty string if the underlying class is
1296
* anonymous.
1297
*
1298
* <p>The simple name of an array is the simple name of the
1299
* component type with "[]" appended. In particular the simple
1300
* name of an array whose component type is anonymous is "[]".
1301
*
1302
* @return the simple name of the underlying class
1303
* @since 1.5
1304
*/
1305
public String getSimpleName() {
1306
if (isArray())
1307
return getComponentType().getSimpleName()+"[]";
1308
1309
String simpleName = getSimpleBinaryName();
1310
if (simpleName == null) { // top level class
1311
simpleName = getName();
1312
return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
1313
}
1314
// According to JLS3 "Binary Compatibility" (13.1) the binary
1315
// name of non-package classes (not top level) is the binary
1316
// name of the immediately enclosing class followed by a '$' followed by:
1317
// (for nested and inner classes): the simple name.
1318
// (for local classes): 1 or more digits followed by the simple name.
1319
// (for anonymous classes): 1 or more digits.
1320
1321
// Since getSimpleBinaryName() will strip the binary name of
1322
// the immediatly enclosing class, we are now looking at a
1323
// string that matches the regular expression "\$[0-9]*"
1324
// followed by a simple name (considering the simple of an
1325
// anonymous class to be the empty string).
1326
1327
// Remove leading "\$[0-9]*" from the name
1328
int length = simpleName.length();
1329
if (length < 1 || simpleName.charAt(0) != '$')
1330
throw new InternalError("Malformed class name");
1331
int index = 1;
1332
while (index < length && isAsciiDigit(simpleName.charAt(index)))
1333
index++;
1334
// Eventually, this is the empty string iff this is an anonymous class
1335
return simpleName.substring(index);
1336
}
1337
1338
/**
1339
* Return an informative string for the name of this type.
1340
*
1341
* @return an informative string for the name of this type
1342
* @since 1.8
1343
*/
1344
public String getTypeName() {
1345
if (isArray()) {
1346
try {
1347
Class<?> cl = this;
1348
int dimensions = 0;
1349
while (cl.isArray()) {
1350
dimensions++;
1351
cl = cl.getComponentType();
1352
}
1353
StringBuilder sb = new StringBuilder();
1354
sb.append(cl.getName());
1355
for (int i = 0; i < dimensions; i++) {
1356
sb.append("[]");
1357
}
1358
return sb.toString();
1359
} catch (Throwable e) { /*FALLTHRU*/ }
1360
}
1361
return getName();
1362
}
1363
1364
/**
1365
* Character.isDigit answers {@code true} to some non-ascii
1366
* digits. This one does not.
1367
*/
1368
private static boolean isAsciiDigit(char c) {
1369
return '0' <= c && c <= '9';
1370
}
1371
1372
/**
1373
* Returns the canonical name of the underlying class as
1374
* defined by the Java Language Specification. Returns null if
1375
* the underlying class does not have a canonical name (i.e., if
1376
* it is a local or anonymous class or an array whose component
1377
* type does not have a canonical name).
1378
* @return the canonical name of the underlying class if it exists, and
1379
* {@code null} otherwise.
1380
* @since 1.5
1381
*/
1382
public String getCanonicalName() {
1383
if (isArray()) {
1384
String canonicalName = getComponentType().getCanonicalName();
1385
if (canonicalName != null)
1386
return canonicalName + "[]";
1387
else
1388
return null;
1389
}
1390
if (isLocalOrAnonymousClass())
1391
return null;
1392
Class<?> enclosingClass = getEnclosingClass();
1393
if (enclosingClass == null) { // top level class
1394
return getName();
1395
} else {
1396
String enclosingName = enclosingClass.getCanonicalName();
1397
if (enclosingName == null)
1398
return null;
1399
return enclosingName + "." + getSimpleName();
1400
}
1401
}
1402
1403
/**
1404
* Returns {@code true} if and only if the underlying class
1405
* is an anonymous class.
1406
*
1407
* @return {@code true} if and only if this class is an anonymous class.
1408
* @since 1.5
1409
*/
1410
public boolean isAnonymousClass() {
1411
return "".equals(getSimpleName());
1412
}
1413
1414
/**
1415
* Returns {@code true} if and only if the underlying class
1416
* is a local class.
1417
*
1418
* @return {@code true} if and only if this class is a local class.
1419
* @since 1.5
1420
*/
1421
public boolean isLocalClass() {
1422
return isLocalOrAnonymousClass() && !isAnonymousClass();
1423
}
1424
1425
/**
1426
* Returns {@code true} if and only if the underlying class
1427
* is a member class.
1428
*
1429
* @return {@code true} if and only if this class is a member class.
1430
* @since 1.5
1431
*/
1432
public boolean isMemberClass() {
1433
return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
1434
}
1435
1436
/**
1437
* Returns the "simple binary name" of the underlying class, i.e.,
1438
* the binary name without the leading enclosing class name.
1439
* Returns {@code null} if the underlying class is a top level
1440
* class.
1441
*/
1442
private String getSimpleBinaryName() {
1443
Class<?> enclosingClass = getEnclosingClass();
1444
if (enclosingClass == null) // top level class
1445
return null;
1446
// Otherwise, strip the enclosing class' name
1447
try {
1448
return getName().substring(enclosingClass.getName().length());
1449
} catch (IndexOutOfBoundsException ex) {
1450
throw new InternalError("Malformed class name", ex);
1451
}
1452
}
1453
1454
/**
1455
* Returns {@code true} if this is a local class or an anonymous
1456
* class. Returns {@code false} otherwise.
1457
*/
1458
private boolean isLocalOrAnonymousClass() {
1459
// JVM Spec 4.8.6: A class must have an EnclosingMethod
1460
// attribute if and only if it is a local class or an
1461
// anonymous class.
1462
return getEnclosingMethodInfo() != null;
1463
}
1464
1465
/**
1466
* Returns an array containing {@code Class} objects representing all
1467
* the public classes and interfaces that are members of the class
1468
* represented by this {@code Class} object. This includes public
1469
* class and interface members inherited from superclasses and public class
1470
* and interface members declared by the class. This method returns an
1471
* array of length 0 if this {@code Class} object has no public member
1472
* classes or interfaces. This method also returns an array of length 0 if
1473
* this {@code Class} object represents a primitive type, an array
1474
* class, or void.
1475
*
1476
* @return the array of {@code Class} objects representing the public
1477
* members of this class
1478
* @throws SecurityException
1479
* If a security manager, <i>s</i>, is present and
1480
* the caller's class loader is not the same as or an
1481
* ancestor of the class loader for the current class and
1482
* invocation of {@link SecurityManager#checkPackageAccess
1483
* s.checkPackageAccess()} denies access to the package
1484
* of this class.
1485
*
1486
* @since JDK1.1
1487
*/
1488
@CallerSensitive
1489
public Class<?>[] getClasses() {
1490
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
1491
1492
// Privileged so this implementation can look at DECLARED classes,
1493
// something the caller might not have privilege to do. The code here
1494
// is allowed to look at DECLARED classes because (1) it does not hand
1495
// out anything other than public members and (2) public member access
1496
// has already been ok'd by the SecurityManager.
1497
1498
return java.security.AccessController.doPrivileged(
1499
new java.security.PrivilegedAction<Class<?>[]>() {
1500
public Class<?>[] run() {
1501
List<Class<?>> list = new ArrayList<>();
1502
Class<?> currentClass = Class.this;
1503
while (currentClass != null) {
1504
Class<?>[] members = currentClass.getDeclaredClasses();
1505
for (int i = 0; i < members.length; i++) {
1506
if (Modifier.isPublic(members[i].getModifiers())) {
1507
list.add(members[i]);
1508
}
1509
}
1510
currentClass = currentClass.getSuperclass();
1511
}
1512
return list.toArray(new Class<?>[0]);
1513
}
1514
});
1515
}
1516
1517
1518
/**
1519
* Returns an array containing {@code Field} objects reflecting all
1520
* the accessible public fields of the class or interface represented by
1521
* this {@code Class} object.
1522
*
1523
* <p> If this {@code Class} object represents a class or interface with no
1524
* no accessible public fields, then this method returns an array of length
1525
* 0.
1526
*
1527
* <p> If this {@code Class} object represents a class, then this method
1528
* returns the public fields of the class and of all its superclasses.
1529
*
1530
* <p> If this {@code Class} object represents an interface, then this
1531
* method returns the fields of the interface and of all its
1532
* superinterfaces.
1533
*
1534
* <p> If this {@code Class} object represents an array type, a primitive
1535
* type, or void, then this method returns an array of length 0.
1536
*
1537
* <p> The elements in the returned array are not sorted and are not in any
1538
* particular order.
1539
*
1540
* @return the array of {@code Field} objects representing the
1541
* public fields
1542
* @throws SecurityException
1543
* If a security manager, <i>s</i>, is present and
1544
* the caller's class loader is not the same as or an
1545
* ancestor of the class loader for the current class and
1546
* invocation of {@link SecurityManager#checkPackageAccess
1547
* s.checkPackageAccess()} denies access to the package
1548
* of this class.
1549
*
1550
* @since JDK1.1
1551
* @jls 8.2 Class Members
1552
* @jls 8.3 Field Declarations
1553
*/
1554
@CallerSensitive
1555
public Field[] getFields() throws SecurityException {
1556
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1557
return copyFields(privateGetPublicFields(null));
1558
}
1559
1560
1561
/**
1562
* Returns an array containing {@code Method} objects reflecting all the
1563
* public methods of the class or interface represented by this {@code
1564
* Class} object, including those declared by the class or interface and
1565
* those inherited from superclasses and superinterfaces.
1566
*
1567
* <p> If this {@code Class} object represents a type that has multiple
1568
* public methods with the same name and parameter types, but different
1569
* return types, then the returned array has a {@code Method} object for
1570
* each such method.
1571
*
1572
* <p> If this {@code Class} object represents a type with a class
1573
* initialization method {@code <clinit>}, then the returned array does
1574
* <em>not</em> have a corresponding {@code Method} object.
1575
*
1576
* <p> If this {@code Class} object represents an array type, then the
1577
* returned array has a {@code Method} object for each of the public
1578
* methods inherited by the array type from {@code Object}. It does not
1579
* contain a {@code Method} object for {@code clone()}.
1580
*
1581
* <p> If this {@code Class} object represents an interface then the
1582
* returned array does not contain any implicitly declared methods from
1583
* {@code Object}. Therefore, if no methods are explicitly declared in
1584
* this interface or any of its superinterfaces then the returned array
1585
* has length 0. (Note that a {@code Class} object which represents a class
1586
* always has public methods, inherited from {@code Object}.)
1587
*
1588
* <p> If this {@code Class} object represents a primitive type or void,
1589
* then the returned array has length 0.
1590
*
1591
* <p> Static methods declared in superinterfaces of the class or interface
1592
* represented by this {@code Class} object are not considered members of
1593
* the class or interface.
1594
*
1595
* <p> The elements in the returned array are not sorted and are not in any
1596
* particular order.
1597
*
1598
* @return the array of {@code Method} objects representing the
1599
* public methods of this class
1600
* @throws SecurityException
1601
* If a security manager, <i>s</i>, is present and
1602
* the caller's class loader is not the same as or an
1603
* ancestor of the class loader for the current class and
1604
* invocation of {@link SecurityManager#checkPackageAccess
1605
* s.checkPackageAccess()} denies access to the package
1606
* of this class.
1607
*
1608
* @jls 8.2 Class Members
1609
* @jls 8.4 Method Declarations
1610
* @since JDK1.1
1611
*/
1612
@CallerSensitive
1613
public Method[] getMethods() throws SecurityException {
1614
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1615
return copyMethods(privateGetPublicMethods());
1616
}
1617
1618
1619
/**
1620
* Returns an array containing {@code Constructor} objects reflecting
1621
* all the public constructors of the class represented by this
1622
* {@code Class} object. An array of length 0 is returned if the
1623
* class has no public constructors, or if the class is an array class, or
1624
* if the class reflects a primitive type or void.
1625
*
1626
* Note that while this method returns an array of {@code
1627
* Constructor<T>} objects (that is an array of constructors from
1628
* this class), the return type of this method is {@code
1629
* Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1630
* might be expected. This less informative return type is
1631
* necessary since after being returned from this method, the
1632
* array could be modified to hold {@code Constructor} objects for
1633
* different classes, which would violate the type guarantees of
1634
* {@code Constructor<T>[]}.
1635
*
1636
* @return the array of {@code Constructor} objects representing the
1637
* public constructors of this class
1638
* @throws SecurityException
1639
* If a security manager, <i>s</i>, is present and
1640
* the caller's class loader is not the same as or an
1641
* ancestor of the class loader for the current class and
1642
* invocation of {@link SecurityManager#checkPackageAccess
1643
* s.checkPackageAccess()} denies access to the package
1644
* of this class.
1645
*
1646
* @since JDK1.1
1647
*/
1648
@CallerSensitive
1649
public Constructor<?>[] getConstructors() throws SecurityException {
1650
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1651
return copyConstructors(privateGetDeclaredConstructors(true));
1652
}
1653
1654
1655
/**
1656
* Returns a {@code Field} object that reflects the specified public member
1657
* field of the class or interface represented by this {@code Class}
1658
* object. The {@code name} parameter is a {@code String} specifying the
1659
* simple name of the desired field.
1660
*
1661
* <p> The field to be reflected is determined by the algorithm that
1662
* follows. Let C be the class or interface represented by this object:
1663
*
1664
* <OL>
1665
* <LI> If C declares a public field with the name specified, that is the
1666
* field to be reflected.</LI>
1667
* <LI> If no field was found in step 1 above, this algorithm is applied
1668
* recursively to each direct superinterface of C. The direct
1669
* superinterfaces are searched in the order they were declared.</LI>
1670
* <LI> If no field was found in steps 1 and 2 above, and C has a
1671
* superclass S, then this algorithm is invoked recursively upon S.
1672
* If C has no superclass, then a {@code NoSuchFieldException}
1673
* is thrown.</LI>
1674
* </OL>
1675
*
1676
* <p> If this {@code Class} object represents an array type, then this
1677
* method does not find the {@code length} field of the array type.
1678
*
1679
* @param name the field name
1680
* @return the {@code Field} object of this class specified by
1681
* {@code name}
1682
* @throws NoSuchFieldException if a field with the specified name is
1683
* not found.
1684
* @throws NullPointerException if {@code name} is {@code null}
1685
* @throws SecurityException
1686
* If a security manager, <i>s</i>, is present and
1687
* the caller's class loader is not the same as or an
1688
* ancestor of the class loader for the current class and
1689
* invocation of {@link SecurityManager#checkPackageAccess
1690
* s.checkPackageAccess()} denies access to the package
1691
* of this class.
1692
*
1693
* @since JDK1.1
1694
* @jls 8.2 Class Members
1695
* @jls 8.3 Field Declarations
1696
*/
1697
@CallerSensitive
1698
public Field getField(String name)
1699
throws NoSuchFieldException, SecurityException {
1700
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1701
Field field = getField0(name);
1702
if (field == null) {
1703
throw new NoSuchFieldException(name);
1704
}
1705
return field;
1706
}
1707
1708
1709
/**
1710
* Returns a {@code Method} object that reflects the specified public
1711
* member method of the class or interface represented by this
1712
* {@code Class} object. The {@code name} parameter is a
1713
* {@code String} specifying the simple name of the desired method. The
1714
* {@code parameterTypes} parameter is an array of {@code Class}
1715
* objects that identify the method's formal parameter types, in declared
1716
* order. If {@code parameterTypes} is {@code null}, it is
1717
* treated as if it were an empty array.
1718
*
1719
* <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a
1720
* {@code NoSuchMethodException} is raised. Otherwise, the method to
1721
* be reflected is determined by the algorithm that follows. Let C be the
1722
* class or interface represented by this object:
1723
* <OL>
1724
* <LI> C is searched for a <I>matching method</I>, as defined below. If a
1725
* matching method is found, it is reflected.</LI>
1726
* <LI> If no matching method is found by step 1 then:
1727
* <OL TYPE="a">
1728
* <LI> If C is a class other than {@code Object}, then this algorithm is
1729
* invoked recursively on the superclass of C.</LI>
1730
* <LI> If C is the class {@code Object}, or if C is an interface, then
1731
* the superinterfaces of C (if any) are searched for a matching
1732
* method. If any such method is found, it is reflected.</LI>
1733
* </OL></LI>
1734
* </OL>
1735
*
1736
* <p> To find a matching method in a class or interface C:&nbsp; If C
1737
* declares exactly one public method with the specified name and exactly
1738
* the same formal parameter types, that is the method reflected. If more
1739
* than one such method is found in C, and one of these methods has a
1740
* return type that is more specific than any of the others, that method is
1741
* reflected; otherwise one of the methods is chosen arbitrarily.
1742
*
1743
* <p>Note that there may be more than one matching method in a
1744
* class because while the Java language forbids a class to
1745
* declare multiple methods with the same signature but different
1746
* return types, the Java virtual machine does not. This
1747
* increased flexibility in the virtual machine can be used to
1748
* implement various language features. For example, covariant
1749
* returns can be implemented with {@linkplain
1750
* java.lang.reflect.Method#isBridge bridge methods}; the bridge
1751
* method and the method being overridden would have the same
1752
* signature but different return types.
1753
*
1754
* <p> If this {@code Class} object represents an array type, then this
1755
* method does not find the {@code clone()} method.
1756
*
1757
* <p> Static methods declared in superinterfaces of the class or interface
1758
* represented by this {@code Class} object are not considered members of
1759
* the class or interface.
1760
*
1761
* @param name the name of the method
1762
* @param parameterTypes the list of parameters
1763
* @return the {@code Method} object that matches the specified
1764
* {@code name} and {@code parameterTypes}
1765
* @throws NoSuchMethodException if a matching method is not found
1766
* or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
1767
* @throws NullPointerException if {@code name} is {@code null}
1768
* @throws SecurityException
1769
* If a security manager, <i>s</i>, is present and
1770
* the caller's class loader is not the same as or an
1771
* ancestor of the class loader for the current class and
1772
* invocation of {@link SecurityManager#checkPackageAccess
1773
* s.checkPackageAccess()} denies access to the package
1774
* of this class.
1775
*
1776
* @jls 8.2 Class Members
1777
* @jls 8.4 Method Declarations
1778
* @since JDK1.1
1779
*/
1780
@CallerSensitive
1781
public Method getMethod(String name, Class<?>... parameterTypes)
1782
throws NoSuchMethodException, SecurityException {
1783
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1784
Method method = getMethod0(name, parameterTypes, true);
1785
if (method == null) {
1786
throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
1787
}
1788
return method;
1789
}
1790
1791
1792
/**
1793
* Returns a {@code Constructor} object that reflects the specified
1794
* public constructor of the class represented by this {@code Class}
1795
* object. The {@code parameterTypes} parameter is an array of
1796
* {@code Class} objects that identify the constructor's formal
1797
* parameter types, in declared order.
1798
*
1799
* If this {@code Class} object represents an inner class
1800
* declared in a non-static context, the formal parameter types
1801
* include the explicit enclosing instance as the first parameter.
1802
*
1803
* <p> The constructor to reflect is the public constructor of the class
1804
* represented by this {@code Class} object whose formal parameter
1805
* types match those specified by {@code parameterTypes}.
1806
*
1807
* @param parameterTypes the parameter array
1808
* @return the {@code Constructor} object of the public constructor that
1809
* matches the specified {@code parameterTypes}
1810
* @throws NoSuchMethodException if a matching method is not found.
1811
* @throws SecurityException
1812
* If a security manager, <i>s</i>, is present and
1813
* the caller's class loader is not the same as or an
1814
* ancestor of the class loader for the current class and
1815
* invocation of {@link SecurityManager#checkPackageAccess
1816
* s.checkPackageAccess()} denies access to the package
1817
* of this class.
1818
*
1819
* @since JDK1.1
1820
*/
1821
@CallerSensitive
1822
public Constructor<T> getConstructor(Class<?>... parameterTypes)
1823
throws NoSuchMethodException, SecurityException {
1824
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1825
return getConstructor0(parameterTypes, Member.PUBLIC);
1826
}
1827
1828
1829
/**
1830
* Returns an array of {@code Class} objects reflecting all the
1831
* classes and interfaces declared as members of the class represented by
1832
* this {@code Class} object. This includes public, protected, default
1833
* (package) access, and private classes and interfaces declared by the
1834
* class, but excludes inherited classes and interfaces. This method
1835
* returns an array of length 0 if the class declares no classes or
1836
* interfaces as members, or if this {@code Class} object represents a
1837
* primitive type, an array class, or void.
1838
*
1839
* @return the array of {@code Class} objects representing all the
1840
* declared members of this class
1841
* @throws SecurityException
1842
* If a security manager, <i>s</i>, is present and any of the
1843
* following conditions is met:
1844
*
1845
* <ul>
1846
*
1847
* <li> the caller's class loader is not the same as the
1848
* class loader of this class and invocation of
1849
* {@link SecurityManager#checkPermission
1850
* s.checkPermission} method with
1851
* {@code RuntimePermission("accessDeclaredMembers")}
1852
* denies access to the declared classes within this class
1853
*
1854
* <li> the caller's class loader is not the same as or an
1855
* ancestor of the class loader for the current class and
1856
* invocation of {@link SecurityManager#checkPackageAccess
1857
* s.checkPackageAccess()} denies access to the package
1858
* of this class
1859
*
1860
* </ul>
1861
*
1862
* @since JDK1.1
1863
*/
1864
@CallerSensitive
1865
public Class<?>[] getDeclaredClasses() throws SecurityException {
1866
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
1867
return getDeclaredClasses0();
1868
}
1869
1870
1871
/**
1872
* Returns an array of {@code Field} objects reflecting all the fields
1873
* declared by the class or interface represented by this
1874
* {@code Class} object. This includes public, protected, default
1875
* (package) access, and private fields, but excludes inherited fields.
1876
*
1877
* <p> If this {@code Class} object represents a class or interface with no
1878
* declared fields, then this method returns an array of length 0.
1879
*
1880
* <p> If this {@code Class} object represents an array type, a primitive
1881
* type, or void, then this method returns an array of length 0.
1882
*
1883
* <p> The elements in the returned array are not sorted and are not in any
1884
* particular order.
1885
*
1886
* @return the array of {@code Field} objects representing all the
1887
* declared fields of this class
1888
* @throws SecurityException
1889
* If a security manager, <i>s</i>, is present and any of the
1890
* following conditions is met:
1891
*
1892
* <ul>
1893
*
1894
* <li> the caller's class loader is not the same as the
1895
* class loader of this class and invocation of
1896
* {@link SecurityManager#checkPermission
1897
* s.checkPermission} method with
1898
* {@code RuntimePermission("accessDeclaredMembers")}
1899
* denies access to the declared fields within this class
1900
*
1901
* <li> the caller's class loader is not the same as or an
1902
* ancestor of the class loader for the current class and
1903
* invocation of {@link SecurityManager#checkPackageAccess
1904
* s.checkPackageAccess()} denies access to the package
1905
* of this class
1906
*
1907
* </ul>
1908
*
1909
* @since JDK1.1
1910
* @jls 8.2 Class Members
1911
* @jls 8.3 Field Declarations
1912
*/
1913
@CallerSensitive
1914
public Field[] getDeclaredFields() throws SecurityException {
1915
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1916
return copyFields(privateGetDeclaredFields(false));
1917
}
1918
1919
1920
/**
1921
*
1922
* Returns an array containing {@code Method} objects reflecting all the
1923
* declared methods of the class or interface represented by this {@code
1924
* Class} object, including public, protected, default (package)
1925
* access, and private methods, but excluding inherited methods.
1926
*
1927
* <p> If this {@code Class} object represents a type that has multiple
1928
* declared methods with the same name and parameter types, but different
1929
* return types, then the returned array has a {@code Method} object for
1930
* each such method.
1931
*
1932
* <p> If this {@code Class} object represents a type that has a class
1933
* initialization method {@code <clinit>}, then the returned array does
1934
* <em>not</em> have a corresponding {@code Method} object.
1935
*
1936
* <p> If this {@code Class} object represents a class or interface with no
1937
* declared methods, then the returned array has length 0.
1938
*
1939
* <p> If this {@code Class} object represents an array type, a primitive
1940
* type, or void, then the returned array has length 0.
1941
*
1942
* <p> The elements in the returned array are not sorted and are not in any
1943
* particular order.
1944
*
1945
* @return the array of {@code Method} objects representing all the
1946
* declared methods of this class
1947
* @throws SecurityException
1948
* If a security manager, <i>s</i>, is present and any of the
1949
* following conditions is met:
1950
*
1951
* <ul>
1952
*
1953
* <li> the caller's class loader is not the same as the
1954
* class loader of this class and invocation of
1955
* {@link SecurityManager#checkPermission
1956
* s.checkPermission} method with
1957
* {@code RuntimePermission("accessDeclaredMembers")}
1958
* denies access to the declared methods within this class
1959
*
1960
* <li> the caller's class loader is not the same as or an
1961
* ancestor of the class loader for the current class and
1962
* invocation of {@link SecurityManager#checkPackageAccess
1963
* s.checkPackageAccess()} denies access to the package
1964
* of this class
1965
*
1966
* </ul>
1967
*
1968
* @jls 8.2 Class Members
1969
* @jls 8.4 Method Declarations
1970
* @since JDK1.1
1971
*/
1972
@CallerSensitive
1973
public Method[] getDeclaredMethods() throws SecurityException {
1974
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1975
return copyMethods(privateGetDeclaredMethods(false));
1976
}
1977
1978
1979
/**
1980
* Returns an array of {@code Constructor} objects reflecting all the
1981
* constructors declared by the class represented by this
1982
* {@code Class} object. These are public, protected, default
1983
* (package) access, and private constructors. The elements in the array
1984
* returned are not sorted and are not in any particular order. If the
1985
* class has a default constructor, it is included in the returned array.
1986
* This method returns an array of length 0 if this {@code Class}
1987
* object represents an interface, a primitive type, an array class, or
1988
* void.
1989
*
1990
* <p> See <em>The Java Language Specification</em>, section 8.2.
1991
*
1992
* @return the array of {@code Constructor} objects representing all the
1993
* declared constructors of this class
1994
* @throws SecurityException
1995
* If a security manager, <i>s</i>, is present and any of the
1996
* following conditions is met:
1997
*
1998
* <ul>
1999
*
2000
* <li> the caller's class loader is not the same as the
2001
* class loader of this class and invocation of
2002
* {@link SecurityManager#checkPermission
2003
* s.checkPermission} method with
2004
* {@code RuntimePermission("accessDeclaredMembers")}
2005
* denies access to the declared constructors within this class
2006
*
2007
* <li> the caller's class loader is not the same as or an
2008
* ancestor of the class loader for the current class and
2009
* invocation of {@link SecurityManager#checkPackageAccess
2010
* s.checkPackageAccess()} denies access to the package
2011
* of this class
2012
*
2013
* </ul>
2014
*
2015
* @since JDK1.1
2016
*/
2017
@CallerSensitive
2018
public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
2019
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2020
return copyConstructors(privateGetDeclaredConstructors(false));
2021
}
2022
2023
2024
/**
2025
* Returns a {@code Field} object that reflects the specified declared
2026
* field of the class or interface represented by this {@code Class}
2027
* object. The {@code name} parameter is a {@code String} that specifies
2028
* the simple name of the desired field.
2029
*
2030
* <p> If this {@code Class} object represents an array type, then this
2031
* method does not find the {@code length} field of the array type.
2032
*
2033
* @param name the name of the field
2034
* @return the {@code Field} object for the specified field in this
2035
* class
2036
* @throws NoSuchFieldException if a field with the specified name is
2037
* not found.
2038
* @throws NullPointerException if {@code name} is {@code null}
2039
* @throws SecurityException
2040
* If a security manager, <i>s</i>, is present and any of the
2041
* following conditions is met:
2042
*
2043
* <ul>
2044
*
2045
* <li> the caller's class loader is not the same as the
2046
* class loader of this class and invocation of
2047
* {@link SecurityManager#checkPermission
2048
* s.checkPermission} method with
2049
* {@code RuntimePermission("accessDeclaredMembers")}
2050
* denies access to the declared field
2051
*
2052
* <li> the caller's class loader is not the same as or an
2053
* ancestor of the class loader for the current class and
2054
* invocation of {@link SecurityManager#checkPackageAccess
2055
* s.checkPackageAccess()} denies access to the package
2056
* of this class
2057
*
2058
* </ul>
2059
*
2060
* @since JDK1.1
2061
* @jls 8.2 Class Members
2062
* @jls 8.3 Field Declarations
2063
*/
2064
@CallerSensitive
2065
public Field getDeclaredField(String name)
2066
throws NoSuchFieldException, SecurityException {
2067
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2068
Field field = searchFields(privateGetDeclaredFields(false), name);
2069
if (field == null) {
2070
throw new NoSuchFieldException(name);
2071
}
2072
return field;
2073
}
2074
2075
2076
/**
2077
* Returns a {@code Method} object that reflects the specified
2078
* declared method of the class or interface represented by this
2079
* {@code Class} object. The {@code name} parameter is a
2080
* {@code String} that specifies the simple name of the desired
2081
* method, and the {@code parameterTypes} parameter is an array of
2082
* {@code Class} objects that identify the method's formal parameter
2083
* types, in declared order. If more than one method with the same
2084
* parameter types is declared in a class, and one of these methods has a
2085
* return type that is more specific than any of the others, that method is
2086
* returned; otherwise one of the methods is chosen arbitrarily. If the
2087
* name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2088
* is raised.
2089
*
2090
* <p> If this {@code Class} object represents an array type, then this
2091
* method does not find the {@code clone()} method.
2092
*
2093
* @param name the name of the method
2094
* @param parameterTypes the parameter array
2095
* @return the {@code Method} object for the method of this class
2096
* matching the specified name and parameters
2097
* @throws NoSuchMethodException if a matching method is not found.
2098
* @throws NullPointerException if {@code name} is {@code null}
2099
* @throws SecurityException
2100
* If a security manager, <i>s</i>, is present and any of the
2101
* following conditions is met:
2102
*
2103
* <ul>
2104
*
2105
* <li> the caller's class loader is not the same as the
2106
* class loader of this class and invocation of
2107
* {@link SecurityManager#checkPermission
2108
* s.checkPermission} method with
2109
* {@code RuntimePermission("accessDeclaredMembers")}
2110
* denies access to the declared method
2111
*
2112
* <li> the caller's class loader is not the same as or an
2113
* ancestor of the class loader for the current class and
2114
* invocation of {@link SecurityManager#checkPackageAccess
2115
* s.checkPackageAccess()} denies access to the package
2116
* of this class
2117
*
2118
* </ul>
2119
*
2120
* @jls 8.2 Class Members
2121
* @jls 8.4 Method Declarations
2122
* @since JDK1.1
2123
*/
2124
@CallerSensitive
2125
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2126
throws NoSuchMethodException, SecurityException {
2127
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2128
Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2129
if (method == null) {
2130
throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
2131
}
2132
return method;
2133
}
2134
2135
2136
/**
2137
* Returns a {@code Constructor} object that reflects the specified
2138
* constructor of the class or interface represented by this
2139
* {@code Class} object. The {@code parameterTypes} parameter is
2140
* an array of {@code Class} objects that identify the constructor's
2141
* formal parameter types, in declared order.
2142
*
2143
* If this {@code Class} object represents an inner class
2144
* declared in a non-static context, the formal parameter types
2145
* include the explicit enclosing instance as the first parameter.
2146
*
2147
* @param parameterTypes the parameter array
2148
* @return The {@code Constructor} object for the constructor with the
2149
* specified parameter list
2150
* @throws NoSuchMethodException if a matching method is not found.
2151
* @throws SecurityException
2152
* If a security manager, <i>s</i>, is present and any of the
2153
* following conditions is met:
2154
*
2155
* <ul>
2156
*
2157
* <li> the caller's class loader is not the same as the
2158
* class loader of this class and invocation of
2159
* {@link SecurityManager#checkPermission
2160
* s.checkPermission} method with
2161
* {@code RuntimePermission("accessDeclaredMembers")}
2162
* denies access to the declared constructor
2163
*
2164
* <li> the caller's class loader is not the same as or an
2165
* ancestor of the class loader for the current class and
2166
* invocation of {@link SecurityManager#checkPackageAccess
2167
* s.checkPackageAccess()} denies access to the package
2168
* of this class
2169
*
2170
* </ul>
2171
*
2172
* @since JDK1.1
2173
*/
2174
@CallerSensitive
2175
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2176
throws NoSuchMethodException, SecurityException {
2177
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2178
return getConstructor0(parameterTypes, Member.DECLARED);
2179
}
2180
2181
/**
2182
* Finds a resource with a given name. The rules for searching resources
2183
* associated with a given class are implemented by the defining
2184
* {@linkplain ClassLoader class loader} of the class. This method
2185
* delegates to this object's class loader. If this object was loaded by
2186
* the bootstrap class loader, the method delegates to {@link
2187
* ClassLoader#getSystemResourceAsStream}.
2188
*
2189
* <p> Before delegation, an absolute resource name is constructed from the
2190
* given resource name using this algorithm:
2191
*
2192
* <ul>
2193
*
2194
* <li> If the {@code name} begins with a {@code '/'}
2195
* (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2196
* portion of the {@code name} following the {@code '/'}.
2197
*
2198
* <li> Otherwise, the absolute name is of the following form:
2199
*
2200
* <blockquote>
2201
* {@code modified_package_name/name}
2202
* </blockquote>
2203
*
2204
* <p> Where the {@code modified_package_name} is the package name of this
2205
* object with {@code '/'} substituted for {@code '.'}
2206
* (<tt>'&#92;u002e'</tt>).
2207
*
2208
* </ul>
2209
*
2210
* @param name name of the desired resource
2211
* @return A {@link java.io.InputStream} object or {@code null} if
2212
* no resource with this name is found
2213
* @throws NullPointerException If {@code name} is {@code null}
2214
* @since JDK1.1
2215
*/
2216
public InputStream getResourceAsStream(String name) {
2217
name = resolveName(name);
2218
ClassLoader cl = getClassLoader0();
2219
if (cl==null) {
2220
// A system class.
2221
return ClassLoader.getSystemResourceAsStream(name);
2222
}
2223
return cl.getResourceAsStream(name);
2224
}
2225
2226
/**
2227
* Finds a resource with a given name. The rules for searching resources
2228
* associated with a given class are implemented by the defining
2229
* {@linkplain ClassLoader class loader} of the class. This method
2230
* delegates to this object's class loader. If this object was loaded by
2231
* the bootstrap class loader, the method delegates to {@link
2232
* ClassLoader#getSystemResource}.
2233
*
2234
* <p> Before delegation, an absolute resource name is constructed from the
2235
* given resource name using this algorithm:
2236
*
2237
* <ul>
2238
*
2239
* <li> If the {@code name} begins with a {@code '/'}
2240
* (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2241
* portion of the {@code name} following the {@code '/'}.
2242
*
2243
* <li> Otherwise, the absolute name is of the following form:
2244
*
2245
* <blockquote>
2246
* {@code modified_package_name/name}
2247
* </blockquote>
2248
*
2249
* <p> Where the {@code modified_package_name} is the package name of this
2250
* object with {@code '/'} substituted for {@code '.'}
2251
* (<tt>'&#92;u002e'</tt>).
2252
*
2253
* </ul>
2254
*
2255
* @param name name of the desired resource
2256
* @return A {@link java.net.URL} object or {@code null} if no
2257
* resource with this name is found
2258
* @since JDK1.1
2259
*/
2260
public java.net.URL getResource(String name) {
2261
name = resolveName(name);
2262
ClassLoader cl = getClassLoader0();
2263
if (cl==null) {
2264
// A system class.
2265
return ClassLoader.getSystemResource(name);
2266
}
2267
return cl.getResource(name);
2268
}
2269
2270
2271
2272
/** protection domain returned when the internal domain is null */
2273
private static java.security.ProtectionDomain allPermDomain;
2274
2275
2276
/**
2277
* Returns the {@code ProtectionDomain} of this class. If there is a
2278
* security manager installed, this method first calls the security
2279
* manager's {@code checkPermission} method with a
2280
* {@code RuntimePermission("getProtectionDomain")} permission to
2281
* ensure it's ok to get the
2282
* {@code ProtectionDomain}.
2283
*
2284
* @return the ProtectionDomain of this class
2285
*
2286
* @throws SecurityException
2287
* if a security manager exists and its
2288
* {@code checkPermission} method doesn't allow
2289
* getting the ProtectionDomain.
2290
*
2291
* @see java.security.ProtectionDomain
2292
* @see SecurityManager#checkPermission
2293
* @see java.lang.RuntimePermission
2294
* @since 1.2
2295
*/
2296
public java.security.ProtectionDomain getProtectionDomain() {
2297
SecurityManager sm = System.getSecurityManager();
2298
if (sm != null) {
2299
sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2300
}
2301
java.security.ProtectionDomain pd = getProtectionDomain0();
2302
if (pd == null) {
2303
if (allPermDomain == null) {
2304
java.security.Permissions perms =
2305
new java.security.Permissions();
2306
perms.add(SecurityConstants.ALL_PERMISSION);
2307
allPermDomain =
2308
new java.security.ProtectionDomain(null, perms);
2309
}
2310
pd = allPermDomain;
2311
}
2312
return pd;
2313
}
2314
2315
2316
/**
2317
* Returns the ProtectionDomain of this class.
2318
*/
2319
private native java.security.ProtectionDomain getProtectionDomain0();
2320
2321
/*
2322
* Return the Virtual Machine's Class object for the named
2323
* primitive type.
2324
*/
2325
static native Class<?> getPrimitiveClass(String name);
2326
2327
/*
2328
* Check if client is allowed to access members. If access is denied,
2329
* throw a SecurityException.
2330
*
2331
* This method also enforces package access.
2332
*
2333
* <p> Default policy: allow all clients access with normal Java access
2334
* control.
2335
*/
2336
private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
2337
final SecurityManager s = System.getSecurityManager();
2338
if (s != null) {
2339
/* Default policy allows access to all {@link Member#PUBLIC} members,
2340
* as well as access to classes that have the same class loader as the caller.
2341
* In all other cases, it requires RuntimePermission("accessDeclaredMembers")
2342
* permission.
2343
*/
2344
final ClassLoader ccl = ClassLoader.getClassLoader(caller);
2345
final ClassLoader cl = getClassLoader0();
2346
if (which != Member.PUBLIC) {
2347
if (ccl != cl) {
2348
s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
2349
}
2350
}
2351
this.checkPackageAccess(ccl, checkProxyInterfaces);
2352
}
2353
}
2354
2355
/*
2356
* Checks if a client loaded in ClassLoader ccl is allowed to access this
2357
* class under the current package access policy. If access is denied,
2358
* throw a SecurityException.
2359
*/
2360
private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {
2361
final SecurityManager s = System.getSecurityManager();
2362
if (s != null) {
2363
final ClassLoader cl = getClassLoader0();
2364
2365
if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
2366
String name = this.getName();
2367
int i = name.lastIndexOf('.');
2368
if (i != -1) {
2369
// skip the package access check on a proxy class in default proxy package
2370
String pkg = name.substring(0, i);
2371
if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
2372
s.checkPackageAccess(pkg);
2373
}
2374
}
2375
}
2376
// check package access on the proxy interfaces
2377
if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
2378
ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
2379
}
2380
}
2381
}
2382
2383
/**
2384
* Add a package name prefix if the name is not absolute Remove leading "/"
2385
* if name is absolute
2386
*/
2387
private String resolveName(String name) {
2388
if (name == null) {
2389
return name;
2390
}
2391
if (!name.startsWith("/")) {
2392
Class<?> c = this;
2393
while (c.isArray()) {
2394
c = c.getComponentType();
2395
}
2396
String baseName = c.getName();
2397
int index = baseName.lastIndexOf('.');
2398
if (index != -1) {
2399
name = baseName.substring(0, index).replace('.', '/')
2400
+"/"+name;
2401
}
2402
} else {
2403
name = name.substring(1);
2404
}
2405
return name;
2406
}
2407
2408
/**
2409
* Atomic operations support.
2410
*/
2411
private static class Atomic {
2412
// initialize Unsafe machinery here, since we need to call Class.class instance method
2413
// and have to avoid calling it in the static initializer of the Class class...
2414
private static final Unsafe unsafe = Unsafe.getUnsafe();
2415
// offset of Class.reflectionData instance field
2416
private static final long reflectionDataOffset;
2417
// offset of Class.annotationType instance field
2418
private static final long annotationTypeOffset;
2419
// offset of Class.annotationData instance field
2420
private static final long annotationDataOffset;
2421
2422
static {
2423
Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches
2424
reflectionDataOffset = objectFieldOffset(fields, "reflectionData");
2425
annotationTypeOffset = objectFieldOffset(fields, "annotationType");
2426
annotationDataOffset = objectFieldOffset(fields, "annotationData");
2427
}
2428
2429
private static long objectFieldOffset(Field[] fields, String fieldName) {
2430
Field field = searchFields(fields, fieldName);
2431
if (field == null) {
2432
throw new Error("No " + fieldName + " field found in java.lang.Class");
2433
}
2434
return unsafe.objectFieldOffset(field);
2435
}
2436
2437
static <T> boolean casReflectionData(Class<?> clazz,
2438
SoftReference<ReflectionData<T>> oldData,
2439
SoftReference<ReflectionData<T>> newData) {
2440
return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
2441
}
2442
2443
static <T> boolean casAnnotationType(Class<?> clazz,
2444
AnnotationType oldType,
2445
AnnotationType newType) {
2446
return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);
2447
}
2448
2449
static <T> boolean casAnnotationData(Class<?> clazz,
2450
AnnotationData oldData,
2451
AnnotationData newData) {
2452
return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData);
2453
}
2454
}
2455
2456
/**
2457
* Reflection support.
2458
*/
2459
2460
// Caches for certain reflective results
2461
private static boolean useCaches = true;
2462
2463
// reflection data that might get invalidated when JVM TI RedefineClasses() is called
2464
private static class ReflectionData<T> {
2465
volatile Field[] declaredFields;
2466
volatile Field[] publicFields;
2467
volatile Method[] declaredMethods;
2468
volatile Method[] publicMethods;
2469
volatile Constructor<T>[] declaredConstructors;
2470
volatile Constructor<T>[] publicConstructors;
2471
// Intermediate results for getFields and getMethods
2472
volatile Field[] declaredPublicFields;
2473
volatile Method[] declaredPublicMethods;
2474
volatile Class<?>[] interfaces;
2475
2476
// Value of classRedefinedCount when we created this ReflectionData instance
2477
final int redefinedCount;
2478
2479
ReflectionData(int redefinedCount) {
2480
this.redefinedCount = redefinedCount;
2481
}
2482
}
2483
2484
private volatile transient SoftReference<ReflectionData<T>> reflectionData;
2485
2486
// Incremented by the VM on each call to JVM TI RedefineClasses()
2487
// that redefines this class or a superclass.
2488
private volatile transient int classRedefinedCount = 0;
2489
2490
// Lazily create and cache ReflectionData
2491
private ReflectionData<T> reflectionData() {
2492
SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2493
int classRedefinedCount = this.classRedefinedCount;
2494
ReflectionData<T> rd;
2495
if (useCaches &&
2496
reflectionData != null &&
2497
(rd = reflectionData.get()) != null &&
2498
rd.redefinedCount == classRedefinedCount) {
2499
return rd;
2500
}
2501
// else no SoftReference or cleared SoftReference or stale ReflectionData
2502
// -> create and replace new instance
2503
return newReflectionData(reflectionData, classRedefinedCount);
2504
}
2505
2506
private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2507
int classRedefinedCount) {
2508
if (!useCaches) return null;
2509
2510
while (true) {
2511
ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2512
// try to CAS it...
2513
if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2514
return rd;
2515
}
2516
// else retry
2517
oldReflectionData = this.reflectionData;
2518
classRedefinedCount = this.classRedefinedCount;
2519
if (oldReflectionData != null &&
2520
(rd = oldReflectionData.get()) != null &&
2521
rd.redefinedCount == classRedefinedCount) {
2522
return rd;
2523
}
2524
}
2525
}
2526
2527
// Generic signature handling
2528
private native String getGenericSignature0();
2529
2530
// Generic info repository; lazily initialized
2531
private volatile transient ClassRepository genericInfo;
2532
2533
// accessor for factory
2534
private GenericsFactory getFactory() {
2535
// create scope and factory
2536
return CoreReflectionFactory.make(this, ClassScope.make(this));
2537
}
2538
2539
// accessor for generic info repository;
2540
// generic info is lazily initialized
2541
private ClassRepository getGenericInfo() {
2542
ClassRepository genericInfo = this.genericInfo;
2543
if (genericInfo == null) {
2544
String signature = getGenericSignature0();
2545
if (signature == null) {
2546
genericInfo = ClassRepository.NONE;
2547
} else {
2548
genericInfo = ClassRepository.make(signature, getFactory());
2549
}
2550
this.genericInfo = genericInfo;
2551
}
2552
return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
2553
}
2554
2555
// Annotations handling
2556
native byte[] getRawAnnotations();
2557
// Since 1.8
2558
native byte[] getRawTypeAnnotations();
2559
static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2560
return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2561
}
2562
2563
native ConstantPool getConstantPool();
2564
2565
//
2566
//
2567
// java.lang.reflect.Field handling
2568
//
2569
//
2570
2571
// Returns an array of "root" fields. These Field objects must NOT
2572
// be propagated to the outside world, but must instead be copied
2573
// via ReflectionFactory.copyField.
2574
private Field[] privateGetDeclaredFields(boolean publicOnly) {
2575
checkInitted();
2576
Field[] res;
2577
ReflectionData<T> rd = reflectionData();
2578
if (rd != null) {
2579
res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
2580
if (res != null) return res;
2581
}
2582
// No cached value available; request value from VM
2583
res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
2584
if (rd != null) {
2585
if (publicOnly) {
2586
rd.declaredPublicFields = res;
2587
} else {
2588
rd.declaredFields = res;
2589
}
2590
}
2591
return res;
2592
}
2593
2594
// Returns an array of "root" fields. These Field objects must NOT
2595
// be propagated to the outside world, but must instead be copied
2596
// via ReflectionFactory.copyField.
2597
private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
2598
checkInitted();
2599
Field[] res;
2600
ReflectionData<T> rd = reflectionData();
2601
if (rd != null) {
2602
res = rd.publicFields;
2603
if (res != null) return res;
2604
}
2605
2606
// No cached value available; compute value recursively.
2607
// Traverse in correct order for getField().
2608
List<Field> fields = new ArrayList<>();
2609
if (traversedInterfaces == null) {
2610
traversedInterfaces = new HashSet<>();
2611
}
2612
2613
// Local fields
2614
Field[] tmp = privateGetDeclaredFields(true);
2615
addAll(fields, tmp);
2616
2617
// Direct superinterfaces, recursively
2618
for (Class<?> c : getInterfaces()) {
2619
if (!traversedInterfaces.contains(c)) {
2620
traversedInterfaces.add(c);
2621
addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2622
}
2623
}
2624
2625
// Direct superclass, recursively
2626
if (!isInterface()) {
2627
Class<?> c = getSuperclass();
2628
if (c != null) {
2629
addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2630
}
2631
}
2632
2633
res = new Field[fields.size()];
2634
fields.toArray(res);
2635
if (rd != null) {
2636
rd.publicFields = res;
2637
}
2638
return res;
2639
}
2640
2641
private static void addAll(Collection<Field> c, Field[] o) {
2642
for (int i = 0; i < o.length; i++) {
2643
c.add(o[i]);
2644
}
2645
}
2646
2647
2648
//
2649
//
2650
// java.lang.reflect.Constructor handling
2651
//
2652
//
2653
2654
// Returns an array of "root" constructors. These Constructor
2655
// objects must NOT be propagated to the outside world, but must
2656
// instead be copied via ReflectionFactory.copyConstructor.
2657
private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
2658
checkInitted();
2659
Constructor<T>[] res;
2660
ReflectionData<T> rd = reflectionData();
2661
if (rd != null) {
2662
res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
2663
if (res != null) return res;
2664
}
2665
// No cached value available; request value from VM
2666
if (isInterface()) {
2667
@SuppressWarnings("unchecked")
2668
Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
2669
res = temporaryRes;
2670
} else {
2671
res = getDeclaredConstructors0(publicOnly);
2672
}
2673
if (rd != null) {
2674
if (publicOnly) {
2675
rd.publicConstructors = res;
2676
} else {
2677
rd.declaredConstructors = res;
2678
}
2679
}
2680
return res;
2681
}
2682
2683
//
2684
//
2685
// java.lang.reflect.Method handling
2686
//
2687
//
2688
2689
// Returns an array of "root" methods. These Method objects must NOT
2690
// be propagated to the outside world, but must instead be copied
2691
// via ReflectionFactory.copyMethod.
2692
private Method[] privateGetDeclaredMethods(boolean publicOnly) {
2693
checkInitted();
2694
Method[] res;
2695
ReflectionData<T> rd = reflectionData();
2696
if (rd != null) {
2697
res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
2698
if (res != null) return res;
2699
}
2700
// No cached value available; request value from VM
2701
res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
2702
if (rd != null) {
2703
if (publicOnly) {
2704
rd.declaredPublicMethods = res;
2705
} else {
2706
rd.declaredMethods = res;
2707
}
2708
}
2709
return res;
2710
}
2711
2712
static class MethodArray {
2713
// Don't add or remove methods except by add() or remove() calls.
2714
private Method[] methods;
2715
private int length;
2716
private int defaults;
2717
2718
MethodArray() {
2719
this(20);
2720
}
2721
2722
MethodArray(int initialSize) {
2723
if (initialSize < 2)
2724
throw new IllegalArgumentException("Size should be 2 or more");
2725
2726
methods = new Method[initialSize];
2727
length = 0;
2728
defaults = 0;
2729
}
2730
2731
boolean hasDefaults() {
2732
return defaults != 0;
2733
}
2734
2735
void add(Method m) {
2736
if (length == methods.length) {
2737
methods = Arrays.copyOf(methods, 2 * methods.length);
2738
}
2739
methods[length++] = m;
2740
2741
if (m != null && m.isDefault())
2742
defaults++;
2743
}
2744
2745
void addAll(Method[] ma) {
2746
for (int i = 0; i < ma.length; i++) {
2747
add(ma[i]);
2748
}
2749
}
2750
2751
void addAll(MethodArray ma) {
2752
for (int i = 0; i < ma.length(); i++) {
2753
add(ma.get(i));
2754
}
2755
}
2756
2757
void addIfNotPresent(Method newMethod) {
2758
for (int i = 0; i < length; i++) {
2759
Method m = methods[i];
2760
if (m == newMethod || (m != null && m.equals(newMethod))) {
2761
return;
2762
}
2763
}
2764
add(newMethod);
2765
}
2766
2767
void addAllIfNotPresent(MethodArray newMethods) {
2768
for (int i = 0; i < newMethods.length(); i++) {
2769
Method m = newMethods.get(i);
2770
if (m != null) {
2771
addIfNotPresent(m);
2772
}
2773
}
2774
}
2775
2776
/* Add Methods declared in an interface to this MethodArray.
2777
* Static methods declared in interfaces are not inherited.
2778
*/
2779
void addInterfaceMethods(Method[] methods) {
2780
for (Method candidate : methods) {
2781
if (!Modifier.isStatic(candidate.getModifiers())) {
2782
add(candidate);
2783
}
2784
}
2785
}
2786
2787
int length() {
2788
return length;
2789
}
2790
2791
Method get(int i) {
2792
return methods[i];
2793
}
2794
2795
Method getFirst() {
2796
for (Method m : methods)
2797
if (m != null)
2798
return m;
2799
return null;
2800
}
2801
2802
void removeByNameAndDescriptor(Method toRemove) {
2803
for (int i = 0; i < length; i++) {
2804
Method m = methods[i];
2805
if (m != null && matchesNameAndDescriptor(m, toRemove)) {
2806
remove(i);
2807
}
2808
}
2809
}
2810
2811
private void remove(int i) {
2812
if (methods[i] != null && methods[i].isDefault())
2813
defaults--;
2814
methods[i] = null;
2815
}
2816
2817
private boolean matchesNameAndDescriptor(Method m1, Method m2) {
2818
return m1.getReturnType() == m2.getReturnType() &&
2819
m1.getName() == m2.getName() && // name is guaranteed to be interned
2820
arrayContentsEq(m1.getParameterTypes(),
2821
m2.getParameterTypes());
2822
}
2823
2824
void compactAndTrim() {
2825
int newPos = 0;
2826
// Get rid of null slots
2827
for (int pos = 0; pos < length; pos++) {
2828
Method m = methods[pos];
2829
if (m != null) {
2830
if (pos != newPos) {
2831
methods[newPos] = m;
2832
}
2833
newPos++;
2834
}
2835
}
2836
if (newPos != methods.length) {
2837
methods = Arrays.copyOf(methods, newPos);
2838
}
2839
}
2840
2841
/* Removes all Methods from this MethodArray that have a more specific
2842
* default Method in this MethodArray.
2843
*
2844
* Users of MethodArray are responsible for pruning Methods that have
2845
* a more specific <em>concrete</em> Method.
2846
*/
2847
void removeLessSpecifics() {
2848
if (!hasDefaults())
2849
return;
2850
2851
for (int i = 0; i < length; i++) {
2852
Method m = get(i);
2853
if (m == null || !m.isDefault())
2854
continue;
2855
2856
for (int j = 0; j < length; j++) {
2857
if (i == j)
2858
continue;
2859
2860
Method candidate = get(j);
2861
if (candidate == null)
2862
continue;
2863
2864
if (!matchesNameAndDescriptor(m, candidate))
2865
continue;
2866
2867
if (hasMoreSpecificClass(m, candidate))
2868
remove(j);
2869
}
2870
}
2871
}
2872
2873
Method[] getArray() {
2874
return methods;
2875
}
2876
2877
// Returns true if m1 is more specific than m2
2878
static boolean hasMoreSpecificClass(Method m1, Method m2) {
2879
Class<?> m1Class = m1.getDeclaringClass();
2880
Class<?> m2Class = m2.getDeclaringClass();
2881
return m1Class != m2Class && m2Class.isAssignableFrom(m1Class);
2882
}
2883
}
2884
2885
2886
// Returns an array of "root" methods. These Method objects must NOT
2887
// be propagated to the outside world, but must instead be copied
2888
// via ReflectionFactory.copyMethod.
2889
private Method[] privateGetPublicMethods() {
2890
checkInitted();
2891
Method[] res;
2892
ReflectionData<T> rd = reflectionData();
2893
if (rd != null) {
2894
res = rd.publicMethods;
2895
if (res != null) return res;
2896
}
2897
2898
// No cached value available; compute value recursively.
2899
// Start by fetching public declared methods
2900
MethodArray methods = new MethodArray();
2901
{
2902
Method[] tmp = privateGetDeclaredMethods(true);
2903
methods.addAll(tmp);
2904
}
2905
// Now recur over superclass and direct superinterfaces.
2906
// Go over superinterfaces first so we can more easily filter
2907
// out concrete implementations inherited from superclasses at
2908
// the end.
2909
MethodArray inheritedMethods = new MethodArray();
2910
for (Class<?> i : getInterfaces()) {
2911
inheritedMethods.addInterfaceMethods(i.privateGetPublicMethods());
2912
}
2913
if (!isInterface()) {
2914
Class<?> c = getSuperclass();
2915
if (c != null) {
2916
MethodArray supers = new MethodArray();
2917
supers.addAll(c.privateGetPublicMethods());
2918
// Filter out concrete implementations of any
2919
// interface methods
2920
for (int i = 0; i < supers.length(); i++) {
2921
Method m = supers.get(i);
2922
if (m != null &&
2923
!Modifier.isAbstract(m.getModifiers()) &&
2924
!m.isDefault()) {
2925
inheritedMethods.removeByNameAndDescriptor(m);
2926
}
2927
}
2928
// Insert superclass's inherited methods before
2929
// superinterfaces' to satisfy getMethod's search
2930
// order
2931
supers.addAll(inheritedMethods);
2932
inheritedMethods = supers;
2933
}
2934
}
2935
// Filter out all local methods from inherited ones
2936
for (int i = 0; i < methods.length(); i++) {
2937
Method m = methods.get(i);
2938
inheritedMethods.removeByNameAndDescriptor(m);
2939
}
2940
methods.addAllIfNotPresent(inheritedMethods);
2941
methods.removeLessSpecifics();
2942
methods.compactAndTrim();
2943
res = methods.getArray();
2944
if (rd != null) {
2945
rd.publicMethods = res;
2946
}
2947
return res;
2948
}
2949
2950
2951
//
2952
// Helpers for fetchers of one field, method, or constructor
2953
//
2954
2955
private static Field searchFields(Field[] fields, String name) {
2956
String internedName = name.intern();
2957
for (int i = 0; i < fields.length; i++) {
2958
if (fields[i].getName() == internedName) {
2959
return getReflectionFactory().copyField(fields[i]);
2960
}
2961
}
2962
return null;
2963
}
2964
2965
private Field getField0(String name) throws NoSuchFieldException {
2966
// Note: the intent is that the search algorithm this routine
2967
// uses be equivalent to the ordering imposed by
2968
// privateGetPublicFields(). It fetches only the declared
2969
// public fields for each class, however, to reduce the number
2970
// of Field objects which have to be created for the common
2971
// case where the field being requested is declared in the
2972
// class which is being queried.
2973
Field res;
2974
// Search declared public fields
2975
if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
2976
return res;
2977
}
2978
// Direct superinterfaces, recursively
2979
Class<?>[] interfaces = getInterfaces();
2980
for (int i = 0; i < interfaces.length; i++) {
2981
Class<?> c = interfaces[i];
2982
if ((res = c.getField0(name)) != null) {
2983
return res;
2984
}
2985
}
2986
// Direct superclass, recursively
2987
if (!isInterface()) {
2988
Class<?> c = getSuperclass();
2989
if (c != null) {
2990
if ((res = c.getField0(name)) != null) {
2991
return res;
2992
}
2993
}
2994
}
2995
return null;
2996
}
2997
2998
private static Method searchMethods(Method[] methods,
2999
String name,
3000
Class<?>[] parameterTypes)
3001
{
3002
Method res = null;
3003
String internedName = name.intern();
3004
for (int i = 0; i < methods.length; i++) {
3005
Method m = methods[i];
3006
if (m.getName() == internedName
3007
&& arrayContentsEq(parameterTypes, m.getParameterTypes())
3008
&& (res == null
3009
|| res.getReturnType().isAssignableFrom(m.getReturnType())))
3010
res = m;
3011
}
3012
3013
return (res == null ? res : getReflectionFactory().copyMethod(res));
3014
}
3015
3016
private Method getMethod0(String name, Class<?>[] parameterTypes, boolean includeStaticMethods) {
3017
MethodArray interfaceCandidates = new MethodArray(2);
3018
Method res = privateGetMethodRecursive(name, parameterTypes, includeStaticMethods, interfaceCandidates);
3019
if (res != null)
3020
return res;
3021
3022
// Not found on class or superclass directly
3023
interfaceCandidates.removeLessSpecifics();
3024
return interfaceCandidates.getFirst(); // may be null
3025
}
3026
3027
private Method privateGetMethodRecursive(String name,
3028
Class<?>[] parameterTypes,
3029
boolean includeStaticMethods,
3030
MethodArray allInterfaceCandidates) {
3031
// Note: the intent is that the search algorithm this routine
3032
// uses be equivalent to the ordering imposed by
3033
// privateGetPublicMethods(). It fetches only the declared
3034
// public methods for each class, however, to reduce the
3035
// number of Method objects which have to be created for the
3036
// common case where the method being requested is declared in
3037
// the class which is being queried.
3038
//
3039
// Due to default methods, unless a method is found on a superclass,
3040
// methods declared in any superinterface needs to be considered.
3041
// Collect all candidates declared in superinterfaces in {@code
3042
// allInterfaceCandidates} and select the most specific if no match on
3043
// a superclass is found.
3044
3045
// Must _not_ return root methods
3046
Method res;
3047
// Search declared public methods
3048
if ((res = searchMethods(privateGetDeclaredMethods(true),
3049
name,
3050
parameterTypes)) != null) {
3051
if (includeStaticMethods || !Modifier.isStatic(res.getModifiers()))
3052
return res;
3053
}
3054
// Search superclass's methods
3055
if (!isInterface()) {
3056
Class<? super T> c = getSuperclass();
3057
if (c != null) {
3058
if ((res = c.getMethod0(name, parameterTypes, true)) != null) {
3059
return res;
3060
}
3061
}
3062
}
3063
// Search superinterfaces' methods
3064
Class<?>[] interfaces = getInterfaces();
3065
for (Class<?> c : interfaces)
3066
if ((res = c.getMethod0(name, parameterTypes, false)) != null)
3067
allInterfaceCandidates.add(res);
3068
// Not found
3069
return null;
3070
}
3071
3072
private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3073
int which) throws NoSuchMethodException
3074
{
3075
Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3076
for (Constructor<T> constructor : constructors) {
3077
if (arrayContentsEq(parameterTypes,
3078
constructor.getParameterTypes())) {
3079
return getReflectionFactory().copyConstructor(constructor);
3080
}
3081
}
3082
throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
3083
}
3084
3085
//
3086
// Other helpers and base implementation
3087
//
3088
3089
private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3090
if (a1 == null) {
3091
return a2 == null || a2.length == 0;
3092
}
3093
3094
if (a2 == null) {
3095
return a1.length == 0;
3096
}
3097
3098
if (a1.length != a2.length) {
3099
return false;
3100
}
3101
3102
for (int i = 0; i < a1.length; i++) {
3103
if (a1[i] != a2[i]) {
3104
return false;
3105
}
3106
}
3107
3108
return true;
3109
}
3110
3111
private static Field[] copyFields(Field[] arg) {
3112
Field[] out = new Field[arg.length];
3113
ReflectionFactory fact = getReflectionFactory();
3114
for (int i = 0; i < arg.length; i++) {
3115
out[i] = fact.copyField(arg[i]);
3116
}
3117
return out;
3118
}
3119
3120
private static Method[] copyMethods(Method[] arg) {
3121
Method[] out = new Method[arg.length];
3122
ReflectionFactory fact = getReflectionFactory();
3123
for (int i = 0; i < arg.length; i++) {
3124
out[i] = fact.copyMethod(arg[i]);
3125
}
3126
return out;
3127
}
3128
3129
private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3130
Constructor<U>[] out = arg.clone();
3131
ReflectionFactory fact = getReflectionFactory();
3132
for (int i = 0; i < out.length; i++) {
3133
out[i] = fact.copyConstructor(out[i]);
3134
}
3135
return out;
3136
}
3137
3138
private native Field[] getDeclaredFields0(boolean publicOnly);
3139
private native Method[] getDeclaredMethods0(boolean publicOnly);
3140
private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3141
private native Class<?>[] getDeclaredClasses0();
3142
3143
private static String argumentTypesToString(Class<?>[] argTypes) {
3144
StringBuilder buf = new StringBuilder();
3145
buf.append("(");
3146
if (argTypes != null) {
3147
for (int i = 0; i < argTypes.length; i++) {
3148
if (i > 0) {
3149
buf.append(", ");
3150
}
3151
Class<?> c = argTypes[i];
3152
buf.append((c == null) ? "null" : c.getName());
3153
}
3154
}
3155
buf.append(")");
3156
return buf.toString();
3157
}
3158
3159
/** use serialVersionUID from JDK 1.1 for interoperability */
3160
private static final long serialVersionUID = 3206093459760846163L;
3161
3162
3163
/**
3164
* Class Class is special cased within the Serialization Stream Protocol.
3165
*
3166
* A Class instance is written initially into an ObjectOutputStream in the
3167
* following format:
3168
* <pre>
3169
* {@code TC_CLASS} ClassDescriptor
3170
* A ClassDescriptor is a special cased serialization of
3171
* a {@code java.io.ObjectStreamClass} instance.
3172
* </pre>
3173
* A new handle is generated for the initial time the class descriptor
3174
* is written into the stream. Future references to the class descriptor
3175
* are written as references to the initial class descriptor instance.
3176
*
3177
* @see java.io.ObjectStreamClass
3178
*/
3179
private static final ObjectStreamField[] serialPersistentFields =
3180
new ObjectStreamField[0];
3181
3182
3183
/**
3184
* Returns the assertion status that would be assigned to this
3185
* class if it were to be initialized at the time this method is invoked.
3186
* If this class has had its assertion status set, the most recent
3187
* setting will be returned; otherwise, if any package default assertion
3188
* status pertains to this class, the most recent setting for the most
3189
* specific pertinent package default assertion status is returned;
3190
* otherwise, if this class is not a system class (i.e., it has a
3191
* class loader) its class loader's default assertion status is returned;
3192
* otherwise, the system class default assertion status is returned.
3193
* <p>
3194
* Few programmers will have any need for this method; it is provided
3195
* for the benefit of the JRE itself. (It allows a class to determine at
3196
* the time that it is initialized whether assertions should be enabled.)
3197
* Note that this method is not guaranteed to return the actual
3198
* assertion status that was (or will be) associated with the specified
3199
* class when it was (or will be) initialized.
3200
*
3201
* @return the desired assertion status of the specified class.
3202
* @see java.lang.ClassLoader#setClassAssertionStatus
3203
* @see java.lang.ClassLoader#setPackageAssertionStatus
3204
* @see java.lang.ClassLoader#setDefaultAssertionStatus
3205
* @since 1.4
3206
*/
3207
public boolean desiredAssertionStatus() {
3208
ClassLoader loader = getClassLoader();
3209
// If the loader is null this is a system class, so ask the VM
3210
if (loader == null)
3211
return desiredAssertionStatus0(this);
3212
3213
// If the classloader has been initialized with the assertion
3214
// directives, ask it. Otherwise, ask the VM.
3215
synchronized(loader.assertionLock) {
3216
if (loader.classAssertionStatus != null) {
3217
return loader.desiredAssertionStatus(getName());
3218
}
3219
}
3220
return desiredAssertionStatus0(this);
3221
}
3222
3223
// Retrieves the desired assertion status of this class from the VM
3224
private static native boolean desiredAssertionStatus0(Class<?> clazz);
3225
3226
/**
3227
* Returns true if and only if this class was declared as an enum in the
3228
* source code.
3229
*
3230
* @return true if and only if this class was declared as an enum in the
3231
* source code
3232
* @since 1.5
3233
*/
3234
public boolean isEnum() {
3235
// An enum must both directly extend java.lang.Enum and have
3236
// the ENUM bit set; classes for specialized enum constants
3237
// don't do the former.
3238
return (this.getModifiers() & ENUM) != 0 &&
3239
this.getSuperclass() == java.lang.Enum.class;
3240
}
3241
3242
// Fetches the factory for reflective objects
3243
private static ReflectionFactory getReflectionFactory() {
3244
if (reflectionFactory == null) {
3245
reflectionFactory =
3246
java.security.AccessController.doPrivileged
3247
(new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
3248
}
3249
return reflectionFactory;
3250
}
3251
private static ReflectionFactory reflectionFactory;
3252
3253
// To be able to query system properties as soon as they're available
3254
private static boolean initted = false;
3255
private static void checkInitted() {
3256
if (initted) return;
3257
AccessController.doPrivileged(new PrivilegedAction<Void>() {
3258
public Void run() {
3259
// Tests to ensure the system properties table is fully
3260
// initialized. This is needed because reflection code is
3261
// called very early in the initialization process (before
3262
// command-line arguments have been parsed and therefore
3263
// these user-settable properties installed.) We assume that
3264
// if System.out is non-null then the System class has been
3265
// fully initialized and that the bulk of the startup code
3266
// has been run.
3267
3268
if (System.out == null) {
3269
// java.lang.System not yet fully initialized
3270
return null;
3271
}
3272
3273
// Doesn't use Boolean.getBoolean to avoid class init.
3274
String val =
3275
System.getProperty("sun.reflect.noCaches");
3276
if (val != null && val.equals("true")) {
3277
useCaches = false;
3278
}
3279
3280
initted = true;
3281
return null;
3282
}
3283
});
3284
}
3285
3286
/**
3287
* Returns the elements of this enum class or null if this
3288
* Class object does not represent an enum type.
3289
*
3290
* @return an array containing the values comprising the enum class
3291
* represented by this Class object in the order they're
3292
* declared, or null if this Class object does not
3293
* represent an enum type
3294
* @since 1.5
3295
*/
3296
public T[] getEnumConstants() {
3297
T[] values = getEnumConstantsShared();
3298
return (values != null) ? values.clone() : null;
3299
}
3300
3301
/**
3302
* Returns the elements of this enum class or null if this
3303
* Class object does not represent an enum type;
3304
* identical to getEnumConstants except that the result is
3305
* uncloned, cached, and shared by all callers.
3306
*/
3307
T[] getEnumConstantsShared() {
3308
if (enumConstants == null) {
3309
if (!isEnum()) return null;
3310
try {
3311
final Method values = getMethod("values");
3312
java.security.AccessController.doPrivileged(
3313
new java.security.PrivilegedAction<Void>() {
3314
public Void run() {
3315
values.setAccessible(true);
3316
return null;
3317
}
3318
});
3319
@SuppressWarnings("unchecked")
3320
T[] temporaryConstants = (T[])values.invoke(null);
3321
enumConstants = temporaryConstants;
3322
}
3323
// These can happen when users concoct enum-like classes
3324
// that don't comply with the enum spec.
3325
catch (InvocationTargetException | NoSuchMethodException |
3326
IllegalAccessException ex) { return null; }
3327
}
3328
return enumConstants;
3329
}
3330
private volatile transient T[] enumConstants = null;
3331
3332
/**
3333
* Returns a map from simple name to enum constant. This package-private
3334
* method is used internally by Enum to implement
3335
* {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3336
* efficiently. Note that the map is returned by this method is
3337
* created lazily on first use. Typically it won't ever get created.
3338
*/
3339
Map<String, T> enumConstantDirectory() {
3340
if (enumConstantDirectory == null) {
3341
T[] universe = getEnumConstantsShared();
3342
if (universe == null)
3343
throw new IllegalArgumentException(
3344
getName() + " is not an enum type");
3345
Map<String, T> m = new HashMap<>(2 * universe.length);
3346
for (T constant : universe)
3347
m.put(((Enum<?>)constant).name(), constant);
3348
enumConstantDirectory = m;
3349
}
3350
return enumConstantDirectory;
3351
}
3352
private volatile transient Map<String, T> enumConstantDirectory = null;
3353
3354
/**
3355
* Casts an object to the class or interface represented
3356
* by this {@code Class} object.
3357
*
3358
* @param obj the object to be cast
3359
* @return the object after casting, or null if obj is null
3360
*
3361
* @throws ClassCastException if the object is not
3362
* null and is not assignable to the type T.
3363
*
3364
* @since 1.5
3365
*/
3366
@SuppressWarnings("unchecked")
3367
public T cast(Object obj) {
3368
if (obj != null && !isInstance(obj))
3369
throw new ClassCastException(cannotCastMsg(obj));
3370
return (T) obj;
3371
}
3372
3373
private String cannotCastMsg(Object obj) {
3374
return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3375
}
3376
3377
/**
3378
* Casts this {@code Class} object to represent a subclass of the class
3379
* represented by the specified class object. Checks that the cast
3380
* is valid, and throws a {@code ClassCastException} if it is not. If
3381
* this method succeeds, it always returns a reference to this class object.
3382
*
3383
* <p>This method is useful when a client needs to "narrow" the type of
3384
* a {@code Class} object to pass it to an API that restricts the
3385
* {@code Class} objects that it is willing to accept. A cast would
3386
* generate a compile-time warning, as the correctness of the cast
3387
* could not be checked at runtime (because generic types are implemented
3388
* by erasure).
3389
*
3390
* @param <U> the type to cast this class object to
3391
* @param clazz the class of the type to cast this class object to
3392
* @return this {@code Class} object, cast to represent a subclass of
3393
* the specified class object.
3394
* @throws ClassCastException if this {@code Class} object does not
3395
* represent a subclass of the specified class (here "subclass" includes
3396
* the class itself).
3397
* @since 1.5
3398
*/
3399
@SuppressWarnings("unchecked")
3400
public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3401
if (clazz.isAssignableFrom(this))
3402
return (Class<? extends U>) this;
3403
else
3404
throw new ClassCastException(this.toString());
3405
}
3406
3407
/**
3408
* @throws NullPointerException {@inheritDoc}
3409
* @since 1.5
3410
*/
3411
@SuppressWarnings("unchecked")
3412
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3413
Objects.requireNonNull(annotationClass);
3414
3415
return (A) annotationData().annotations.get(annotationClass);
3416
}
3417
3418
/**
3419
* {@inheritDoc}
3420
* @throws NullPointerException {@inheritDoc}
3421
* @since 1.5
3422
*/
3423
@Override
3424
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3425
return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3426
}
3427
3428
/**
3429
* @throws NullPointerException {@inheritDoc}
3430
* @since 1.8
3431
*/
3432
@Override
3433
public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3434
Objects.requireNonNull(annotationClass);
3435
3436
AnnotationData annotationData = annotationData();
3437
return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
3438
this,
3439
annotationClass);
3440
}
3441
3442
/**
3443
* @since 1.5
3444
*/
3445
public Annotation[] getAnnotations() {
3446
return AnnotationParser.toArray(annotationData().annotations);
3447
}
3448
3449
/**
3450
* @throws NullPointerException {@inheritDoc}
3451
* @since 1.8
3452
*/
3453
@Override
3454
@SuppressWarnings("unchecked")
3455
public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3456
Objects.requireNonNull(annotationClass);
3457
3458
return (A) annotationData().declaredAnnotations.get(annotationClass);
3459
}
3460
3461
/**
3462
* @throws NullPointerException {@inheritDoc}
3463
* @since 1.8
3464
*/
3465
@Override
3466
public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3467
Objects.requireNonNull(annotationClass);
3468
3469
return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
3470
annotationClass);
3471
}
3472
3473
/**
3474
* @since 1.5
3475
*/
3476
public Annotation[] getDeclaredAnnotations() {
3477
return AnnotationParser.toArray(annotationData().declaredAnnotations);
3478
}
3479
3480
// annotation data that might get invalidated when JVM TI RedefineClasses() is called
3481
private static class AnnotationData {
3482
final Map<Class<? extends Annotation>, Annotation> annotations;
3483
final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3484
3485
// Value of classRedefinedCount when we created this AnnotationData instance
3486
final int redefinedCount;
3487
3488
AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
3489
Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
3490
int redefinedCount) {
3491
this.annotations = annotations;
3492
this.declaredAnnotations = declaredAnnotations;
3493
this.redefinedCount = redefinedCount;
3494
}
3495
}
3496
3497
// Annotations cache
3498
@SuppressWarnings("UnusedDeclaration")
3499
private volatile transient AnnotationData annotationData;
3500
3501
private AnnotationData annotationData() {
3502
while (true) { // retry loop
3503
AnnotationData annotationData = this.annotationData;
3504
int classRedefinedCount = this.classRedefinedCount;
3505
if (annotationData != null &&
3506
annotationData.redefinedCount == classRedefinedCount) {
3507
return annotationData;
3508
}
3509
// null or stale annotationData -> optimistically create new instance
3510
AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
3511
// try to install it
3512
if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
3513
// successfully installed new AnnotationData
3514
return newAnnotationData;
3515
}
3516
}
3517
}
3518
3519
private AnnotationData createAnnotationData(int classRedefinedCount) {
3520
Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
3521
AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
3522
Class<?> superClass = getSuperclass();
3523
Map<Class<? extends Annotation>, Annotation> annotations = null;
3524
if (superClass != null) {
3525
Map<Class<? extends Annotation>, Annotation> superAnnotations =
3526
superClass.annotationData().annotations;
3527
for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
3528
Class<? extends Annotation> annotationClass = e.getKey();
3529
if (AnnotationType.getInstance(annotationClass).isInherited()) {
3530
if (annotations == null) { // lazy construction
3531
annotations = new LinkedHashMap<>((Math.max(
3532
declaredAnnotations.size(),
3533
Math.min(12, declaredAnnotations.size() + superAnnotations.size())
3534
) * 4 + 2) / 3
3535
);
3536
}
3537
annotations.put(annotationClass, e.getValue());
3538
}
3539
}
3540
}
3541
if (annotations == null) {
3542
// no inherited annotations -> share the Map with declaredAnnotations
3543
annotations = declaredAnnotations;
3544
} else {
3545
// at least one inherited annotation -> declared may override inherited
3546
annotations.putAll(declaredAnnotations);
3547
}
3548
return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
3549
}
3550
3551
// Annotation types cache their internal (AnnotationType) form
3552
3553
@SuppressWarnings("UnusedDeclaration")
3554
private volatile transient AnnotationType annotationType;
3555
3556
boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3557
return Atomic.casAnnotationType(this, oldType, newType);
3558
}
3559
3560
AnnotationType getAnnotationType() {
3561
return annotationType;
3562
}
3563
3564
Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
3565
return annotationData().declaredAnnotations;
3566
}
3567
3568
/* Backing store of user-defined values pertaining to this class.
3569
* Maintained by the ClassValue class.
3570
*/
3571
transient ClassValue.ClassValueMap classValueMap;
3572
3573
/**
3574
* Returns an {@code AnnotatedType} object that represents the use of a
3575
* type to specify the superclass of the entity represented by this {@code
3576
* Class} object. (The <em>use</em> of type Foo to specify the superclass
3577
* in '... extends Foo' is distinct from the <em>declaration</em> of type
3578
* Foo.)
3579
*
3580
* <p> If this {@code Class} object represents a type whose declaration
3581
* does not explicitly indicate an annotated superclass, then the return
3582
* value is an {@code AnnotatedType} object representing an element with no
3583
* annotations.
3584
*
3585
* <p> If this {@code Class} represents either the {@code Object} class, an
3586
* interface type, an array type, a primitive type, or void, the return
3587
* value is {@code null}.
3588
*
3589
* @return an object representing the superclass
3590
* @since 1.8
3591
*/
3592
public AnnotatedType getAnnotatedSuperclass() {
3593
if (this == Object.class ||
3594
isInterface() ||
3595
isArray() ||
3596
isPrimitive() ||
3597
this == Void.TYPE) {
3598
return null;
3599
}
3600
3601
return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3602
}
3603
3604
/**
3605
* Returns an array of {@code AnnotatedType} objects that represent the use
3606
* of types to specify superinterfaces of the entity represented by this
3607
* {@code Class} object. (The <em>use</em> of type Foo to specify a
3608
* superinterface in '... implements Foo' is distinct from the
3609
* <em>declaration</em> of type Foo.)
3610
*
3611
* <p> If this {@code Class} object represents a class, the return value is
3612
* an array containing objects representing the uses of interface types to
3613
* specify interfaces implemented by the class. The order of the objects in
3614
* the array corresponds to the order of the interface types used in the
3615
* 'implements' clause of the declaration of this {@code Class} object.
3616
*
3617
* <p> If this {@code Class} object represents an interface, the return
3618
* value is an array containing objects representing the uses of interface
3619
* types to specify interfaces directly extended by the interface. The
3620
* order of the objects in the array corresponds to the order of the
3621
* interface types used in the 'extends' clause of the declaration of this
3622
* {@code Class} object.
3623
*
3624
* <p> If this {@code Class} object represents a class or interface whose
3625
* declaration does not explicitly indicate any annotated superinterfaces,
3626
* the return value is an array of length 0.
3627
*
3628
* <p> If this {@code Class} object represents either the {@code Object}
3629
* class, an array type, a primitive type, or void, the return value is an
3630
* array of length 0.
3631
*
3632
* @return an array representing the superinterfaces
3633
* @since 1.8
3634
*/
3635
public AnnotatedType[] getAnnotatedInterfaces() {
3636
return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3637
}
3638
}
3639
3640