blob: fa6971dabfab31431ab7660c24fbd714c01d018e [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
Alan Batemandb4d3832016-03-17 19:04:16 +00002 * Copyright (c) 1994, 2016, Oracle and/or its affiliates. All rights reserved.
J. Duke319a3b92007-12-01 00:00:00 +00003 * 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
Kelly O'Hairfe008ae2010-05-25 15:58:33 -07007 * published by the Free Software Foundation. Oracle designates this
J. Duke319a3b92007-12-01 00:00:00 +00008 * particular file as subject to the "Classpath" exception as provided
Kelly O'Hairfe008ae2010-05-25 15:58:33 -07009 * by Oracle in the LICENSE file that accompanied this code.
J. Duke319a3b92007-12-01 00:00:00 +000010 *
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 *
Kelly O'Hairfe008ae2010-05-25 15:58:33 -070021 * 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.
J. Duke319a3b92007-12-01 00:00:00 +000024 */
25
26package java.lang;
27
Alan Batemandb4d3832016-03-17 19:04:16 +000028import java.lang.annotation.Annotation;
29import java.lang.module.ModuleReader;
Joe Darcybc576242013-03-04 19:42:56 -080030import java.lang.reflect.AnnotatedElement;
J. Duke319a3b92007-12-01 00:00:00 +000031import java.lang.reflect.Array;
32import java.lang.reflect.GenericArrayType;
Joe Darcy7c644b02013-05-22 20:03:45 -070033import java.lang.reflect.GenericDeclaration;
J. Duke319a3b92007-12-01 00:00:00 +000034import java.lang.reflect.Member;
35import java.lang.reflect.Field;
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +010036import java.lang.reflect.Executable;
J. Duke319a3b92007-12-01 00:00:00 +000037import java.lang.reflect.Method;
Alan Batemandb4d3832016-03-17 19:04:16 +000038import java.lang.reflect.Module;
J. Duke319a3b92007-12-01 00:00:00 +000039import java.lang.reflect.Constructor;
J. Duke319a3b92007-12-01 00:00:00 +000040import java.lang.reflect.Modifier;
41import java.lang.reflect.Type;
42import java.lang.reflect.TypeVariable;
43import java.lang.reflect.InvocationTargetException;
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +010044import java.lang.reflect.AnnotatedType;
Alan Batemandb4d3832016-03-17 19:04:16 +000045import java.lang.reflect.Proxy;
J. Duke319a3b92007-12-01 00:00:00 +000046import java.lang.ref.SoftReference;
Alan Batemandb4d3832016-03-17 19:04:16 +000047import java.io.IOException;
J. Duke319a3b92007-12-01 00:00:00 +000048import java.io.InputStream;
49import java.io.ObjectStreamField;
Alan Batemandb4d3832016-03-17 19:04:16 +000050import java.net.URL;
J. Duke319a3b92007-12-01 00:00:00 +000051import java.security.AccessController;
52import java.security.PrivilegedAction;
53import java.util.ArrayList;
54import java.util.Arrays;
55import java.util.Collection;
56import java.util.HashSet;
Peter Levartc7759dc2013-09-19 16:14:13 +020057import java.util.LinkedHashMap;
J. Duke319a3b92007-12-01 00:00:00 +000058import java.util.List;
J. Duke319a3b92007-12-01 00:00:00 +000059import java.util.Set;
60import java.util.Map;
61import java.util.HashMap;
Joel Borggrén-Franck36464f42012-11-28 09:21:37 -080062import java.util.Objects;
Ivan Gerasimove164c862014-08-27 22:08:19 +040063import java.util.StringJoiner;
Alan Batemandb4d3832016-03-17 19:04:16 +000064import jdk.internal.HotSpotIntrinsicCandidate;
65import jdk.internal.loader.BootLoader;
66import jdk.internal.loader.BuiltinClassLoader;
Chris Hegartybdbc4d12015-11-11 09:19:12 +000067import jdk.internal.misc.Unsafe;
Chris Hegartyaa0ef2e2016-01-06 10:01:44 +000068import jdk.internal.misc.VM;
Mandy Chung176ed8d2013-04-16 21:39:52 -070069import sun.reflect.CallerSensitive;
J. Duke319a3b92007-12-01 00:00:00 +000070import sun.reflect.ConstantPool;
71import sun.reflect.Reflection;
72import sun.reflect.ReflectionFactory;
J. Duke319a3b92007-12-01 00:00:00 +000073import sun.reflect.generics.factory.CoreReflectionFactory;
74import sun.reflect.generics.factory.GenericsFactory;
75import sun.reflect.generics.repository.ClassRepository;
76import sun.reflect.generics.repository.MethodRepository;
77import sun.reflect.generics.repository.ConstructorRepository;
78import sun.reflect.generics.scope.ClassScope;
79import sun.security.util.SecurityConstants;
J. Duke319a3b92007-12-01 00:00:00 +000080import sun.reflect.annotation.*;
Mandy Chungd3ccd202012-11-02 16:50:23 -070081import sun.reflect.misc.ReflectUtil;
J. Duke319a3b92007-12-01 00:00:00 +000082
83/**
84 * Instances of the class {@code Class} represent classes and
85 * interfaces in a running Java application. An enum is a kind of
86 * class and an annotation is a kind of interface. Every array also
87 * belongs to a class that is reflected as a {@code Class} object
88 * that is shared by all arrays with the same element type and number
89 * of dimensions. The primitive Java types ({@code boolean},
90 * {@code byte}, {@code char}, {@code short},
91 * {@code int}, {@code long}, {@code float}, and
92 * {@code double}), and the keyword {@code void} are also
93 * represented as {@code Class} objects.
94 *
95 * <p> {@code Class} has no public constructor. Instead {@code Class}
96 * objects are constructed automatically by the Java Virtual Machine as classes
97 * are loaded and by calls to the {@code defineClass} method in the class
98 * loader.
99 *
100 * <p> The following example uses a {@code Class} object to print the
101 * class name of an object:
102 *
Roger Riggs93dcac62013-10-22 17:02:08 -0400103 * <blockquote><pre>
J. Duke319a3b92007-12-01 00:00:00 +0000104 * void printClassName(Object obj) {
105 * System.out.println("The class of " + obj +
106 * " is " + obj.getClass().getName());
107 * }
108 * </pre></blockquote>
109 *
110 * <p> It is also possible to get the {@code Class} object for a named
Jim Holmlundbbf16c02011-04-13 12:16:13 -0700111 * type (or for void) using a class literal. See Section 15.8.2 of
112 * <cite>The Java&trade; Language Specification</cite>.
J. Duke319a3b92007-12-01 00:00:00 +0000113 * For example:
114 *
Roger Riggs93dcac62013-10-22 17:02:08 -0400115 * <blockquote>
J. Duke319a3b92007-12-01 00:00:00 +0000116 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
117 * </blockquote>
118 *
119 * @param <T> the type of the class modeled by this {@code Class}
120 * object. For example, the type of {@code String.class} is {@code
121 * Class<String>}. Use {@code Class<?>} if the class being modeled is
122 * unknown.
123 *
124 * @author unascribed
125 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
Henry Jenea9a7a82014-06-10 16:18:54 -0700126 * @since 1.0
J. Duke319a3b92007-12-01 00:00:00 +0000127 */
Joe Darcy2c7f3d22013-04-08 17:06:20 -0700128public final class Class<T> implements java.io.Serializable,
Joe Darcy7c644b02013-05-22 20:03:45 -0700129 GenericDeclaration,
130 Type,
131 AnnotatedElement {
J. Duke319a3b92007-12-01 00:00:00 +0000132 private static final int ANNOTATION= 0x00002000;
133 private static final int ENUM = 0x00004000;
134 private static final int SYNTHETIC = 0x00001000;
135
136 private static native void registerNatives();
137 static {
138 registerNatives();
139 }
140
141 /*
Coleen Phillimoreaa12c8f2014-06-24 11:23:34 -0400142 * Private constructor. Only the Java Virtual Machine creates Class objects.
143 * This constructor is not used and prevents the default constructor being
144 * generated.
J. Duke319a3b92007-12-01 00:00:00 +0000145 */
Coleen Phillimorecbb6f302014-07-02 16:47:49 -0400146 private Class(ClassLoader loader, Class<?> arrayComponentType) {
Coleen Phillimoreaa12c8f2014-06-24 11:23:34 -0400147 // Initialize final field for classLoader. The initialization value of non-null
148 // prevents future JIT optimizations from assuming this final field is null.
149 classLoader = loader;
Coleen Phillimorecbb6f302014-07-02 16:47:49 -0400150 componentType = arrayComponentType;
Coleen Phillimoreaa12c8f2014-06-24 11:23:34 -0400151 }
J. Duke319a3b92007-12-01 00:00:00 +0000152
153 /**
154 * Converts the object to a string. The string representation is the
155 * string "class" or "interface", followed by a space, and then by the
156 * fully qualified name of the class in the format returned by
157 * {@code getName}. If this {@code Class} object represents a
158 * primitive type, this method returns the name of the primitive type. If
159 * this {@code Class} object represents void this method returns
Joe Darcy9800aaa2015-01-16 14:04:27 -0800160 * "void". If this {@code Class} object represents an array type,
161 * this method returns "class " followed by {@code getName}.
J. Duke319a3b92007-12-01 00:00:00 +0000162 *
163 * @return a string representation of this class object.
164 */
165 public String toString() {
166 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
167 + getName();
168 }
169
Joe Darcy2c7f3d22013-04-08 17:06:20 -0700170 /**
171 * Returns a string describing this {@code Class}, including
172 * information about modifiers and type parameters.
173 *
174 * The string is formatted as a list of type modifiers, if any,
175 * followed by the kind of type (empty string for primitive types
Joe Darcy5cae1dc2013-07-18 23:16:52 -0700176 * and {@code class}, {@code enum}, {@code interface}, or
177 * <code>&#64;</code>{@code interface}, as appropriate), followed
178 * by the type's name, followed by an angle-bracketed
179 * comma-separated list of the type's type parameters, if any.
Joe Darcy2c7f3d22013-04-08 17:06:20 -0700180 *
181 * A space is used to separate modifiers from one another and to
182 * separate any modifiers from the kind of type. The modifiers
183 * occur in canonical order. If there are no type parameters, the
184 * type parameter list is elided.
185 *
Joe Darcy9800aaa2015-01-16 14:04:27 -0800186 * For an array type, the string starts with the type name,
187 * followed by an angle-bracketed comma-separated list of the
188 * type's type parameters, if any, followed by a sequence of
189 * {@code []} characters, one set of brackets per dimension of
190 * the array.
191 *
Joe Darcy2c7f3d22013-04-08 17:06:20 -0700192 * <p>Note that since information about the runtime representation
193 * of a type is being generated, modifiers not present on the
194 * originating source code or illegal on the originating source
195 * code may be present.
196 *
197 * @return a string describing this {@code Class}, including
198 * information about modifiers and type parameters
199 *
200 * @since 1.8
201 */
202 public String toGenericString() {
203 if (isPrimitive()) {
204 return toString();
205 } else {
206 StringBuilder sb = new StringBuilder();
Joe Darcy9800aaa2015-01-16 14:04:27 -0800207 Class<?> component = this;
208 int arrayDepth = 0;
Joe Darcy2c7f3d22013-04-08 17:06:20 -0700209
Joe Darcy9800aaa2015-01-16 14:04:27 -0800210 if (isArray()) {
211 do {
212 arrayDepth++;
213 component = component.getComponentType();
214 } while (component.isArray());
215 sb.append(component.getName());
Joe Darcy2c7f3d22013-04-08 17:06:20 -0700216 } else {
Joe Darcy9800aaa2015-01-16 14:04:27 -0800217 // Class modifiers are a superset of interface modifiers
218 int modifiers = getModifiers() & Modifier.classModifiers();
219 if (modifiers != 0) {
220 sb.append(Modifier.toString(modifiers));
221 sb.append(' ');
222 }
Joe Darcy2c7f3d22013-04-08 17:06:20 -0700223
Joe Darcy9800aaa2015-01-16 14:04:27 -0800224 if (isAnnotation()) {
225 sb.append('@');
226 }
227 if (isInterface()) { // Note: all annotation types are interfaces
228 sb.append("interface");
229 } else {
230 if (isEnum())
231 sb.append("enum");
232 else
233 sb.append("class");
234 }
235 sb.append(' ');
236 sb.append(getName());
237 }
238
239 TypeVariable<?>[] typeparms = component.getTypeParameters();
Joe Darcy2c7f3d22013-04-08 17:06:20 -0700240 if (typeparms.length > 0) {
241 boolean first = true;
242 sb.append('<');
243 for(TypeVariable<?> typeparm: typeparms) {
244 if (!first)
245 sb.append(',');
246 sb.append(typeparm.getTypeName());
247 first = false;
248 }
249 sb.append('>');
250 }
251
Joe Darcy9800aaa2015-01-16 14:04:27 -0800252 for (int i = 0; i < arrayDepth; i++)
253 sb.append("[]");
254
Joe Darcy2c7f3d22013-04-08 17:06:20 -0700255 return sb.toString();
256 }
257 }
J. Duke319a3b92007-12-01 00:00:00 +0000258
259 /**
260 * Returns the {@code Class} object associated with the class or
261 * interface with the given string name. Invoking this method is
262 * equivalent to:
263 *
264 * <blockquote>
265 * {@code Class.forName(className, true, currentLoader)}
266 * </blockquote>
267 *
268 * where {@code currentLoader} denotes the defining class loader of
269 * the current class.
270 *
271 * <p> For example, the following code fragment returns the
272 * runtime {@code Class} descriptor for the class named
273 * {@code java.lang.Thread}:
274 *
275 * <blockquote>
276 * {@code Class t = Class.forName("java.lang.Thread")}
277 * </blockquote>
278 * <p>
279 * A call to {@code forName("X")} causes the class named
280 * {@code X} to be initialized.
281 *
282 * @param className the fully qualified name of the desired class.
283 * @return the {@code Class} object for the class with the
284 * specified name.
285 * @exception LinkageError if the linkage fails
286 * @exception ExceptionInInitializerError if the initialization provoked
287 * by this method fails
288 * @exception ClassNotFoundException if the class cannot be located
289 */
Mandy Chung176ed8d2013-04-16 21:39:52 -0700290 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +0000291 public static Class<?> forName(String className)
292 throws ClassNotFoundException {
Coleen Phillimore3e5a5302014-07-22 16:24:48 +0400293 Class<?> caller = Reflection.getCallerClass();
294 return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
J. Duke319a3b92007-12-01 00:00:00 +0000295 }
296
297
298 /**
299 * Returns the {@code Class} object associated with the class or
300 * interface with the given string name, using the given class loader.
301 * Given the fully qualified name for a class or interface (in the same
302 * format returned by {@code getName}) this method attempts to
303 * locate, load, and link the class or interface. The specified class
304 * loader is used to load the class or interface. If the parameter
305 * {@code loader} is null, the class is loaded through the bootstrap
306 * class loader. The class is initialized only if the
307 * {@code initialize} parameter is {@code true} and if it has
308 * not been initialized earlier.
309 *
310 * <p> If {@code name} denotes a primitive type or void, an attempt
311 * will be made to locate a user-defined class in the unnamed package whose
312 * name is {@code name}. Therefore, this method cannot be used to
313 * obtain any of the {@code Class} objects representing primitive
314 * types or void.
315 *
316 * <p> If {@code name} denotes an array class, the component type of
317 * the array class is loaded but not initialized.
318 *
319 * <p> For example, in an instance method the expression:
320 *
321 * <blockquote>
322 * {@code Class.forName("Foo")}
323 * </blockquote>
324 *
325 * is equivalent to:
326 *
327 * <blockquote>
328 * {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
329 * </blockquote>
330 *
331 * Note that this method throws errors related to loading, linking or
332 * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
333 * Java Language Specification</em>.
334 * Note that this method does not check whether the requested class
335 * is accessible to its caller.
336 *
337 * <p> If the {@code loader} is {@code null}, and a security
338 * manager is present, and the caller's class loader is not null, then this
339 * method calls the security manager's {@code checkPermission} method
340 * with a {@code RuntimePermission("getClassLoader")} permission to
341 * ensure it's ok to access the bootstrap class loader.
342 *
343 * @param name fully qualified name of the desired class
Mandy Chung91088242012-08-24 22:55:49 -0700344 * @param initialize if {@code true} the class will be initialized.
345 * See Section 12.4 of <em>The Java Language Specification</em>.
J. Duke319a3b92007-12-01 00:00:00 +0000346 * @param loader class loader from which the class must be loaded
347 * @return class object representing the desired class
348 *
349 * @exception LinkageError if the linkage fails
350 * @exception ExceptionInInitializerError if the initialization provoked
351 * by this method fails
352 * @exception ClassNotFoundException if the class cannot be located by
353 * the specified class loader
354 *
355 * @see java.lang.Class#forName(String)
356 * @see java.lang.ClassLoader
357 * @since 1.2
358 */
Mandy Chung176ed8d2013-04-16 21:39:52 -0700359 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +0000360 public static Class<?> forName(String name, boolean initialize,
361 ClassLoader loader)
362 throws ClassNotFoundException
363 {
Coleen Phillimore3e5a5302014-07-22 16:24:48 +0400364 Class<?> caller = null;
365 SecurityManager sm = System.getSecurityManager();
366 if (sm != null) {
367 // Reflective call to get caller class is only needed if a security manager
368 // is present. Avoid the overhead of making this call otherwise.
369 caller = Reflection.getCallerClass();
Chris Hegartyaa0ef2e2016-01-06 10:01:44 +0000370 if (VM.isSystemDomainLoader(loader)) {
Coleen Phillimore3e5a5302014-07-22 16:24:48 +0400371 ClassLoader ccl = ClassLoader.getClassLoader(caller);
Chris Hegartyaa0ef2e2016-01-06 10:01:44 +0000372 if (!VM.isSystemDomainLoader(ccl)) {
J. Duke319a3b92007-12-01 00:00:00 +0000373 sm.checkPermission(
374 SecurityConstants.GET_CLASSLOADER_PERMISSION);
375 }
376 }
377 }
Coleen Phillimore3e5a5302014-07-22 16:24:48 +0400378 return forName0(name, initialize, loader, caller);
J. Duke319a3b92007-12-01 00:00:00 +0000379 }
380
Coleen Phillimore3e5a5302014-07-22 16:24:48 +0400381 /** Called after security check for system loader access checks have been made. */
Joe Darcybd9e7da2009-10-06 13:31:41 -0700382 private static native Class<?> forName0(String name, boolean initialize,
Coleen Phillimore3e5a5302014-07-22 16:24:48 +0400383 ClassLoader loader,
384 Class<?> caller)
J. Duke319a3b92007-12-01 00:00:00 +0000385 throws ClassNotFoundException;
386
Alan Batemandb4d3832016-03-17 19:04:16 +0000387
388 /**
389 * Returns the {@code Class} with the given <a href="ClassLoader.html#name">
390 * binary name</a> in the given module.
391 *
392 * <p> This method attempts to locate, load, and link the class or interface.
393 * It does not run the class initializer. If the class is not found, this
394 * method returns {@code null}. </p>
395 *
396 * <p> If the class loader of the given module defines other modules and
397 * the given name is a class defined in a different module, this method
398 * returns {@code null} after the class is loaded. </p>
399 *
400 * <p> This method does not check whether the requested class is
401 * accessible to its caller. </p>
402 *
403 * @apiNote
404 * This method returns {@code null} on failure rather than
405 * throwing a {@link ClassNotFoundException}, as is done by
406 * the {@link #forName(String, boolean, ClassLoader)} method.
407 * The security check is a stack-based permission check if the caller
408 * loads a class in another module.
409 *
410 * @param module A module
411 * @param name The <a href="ClassLoader.html#name">binary name</a>
412 * of the class
413 * @return {@code Class} object of the given name defined in the given module;
414 * {@code null} if not found.
415 *
416 * @throws NullPointerException if the given module or name is {@code null}
417 *
418 * @throws LinkageError if the linkage fails
419 *
420 * @throws SecurityException
421 * <ul>
422 * <li> if the caller is not the specified module and
423 * {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
424 * <li> access to the module content is denied. For example,
425 * permission check will be performed when a class loader calls
426 * {@link ModuleReader#open(String)} to read the bytes of a class file
427 * in a module.</li>
428 * </ul>
429 *
430 * @since 9
431 */
432 @CallerSensitive
433 public static Class<?> forName(Module module, String name) {
434 Objects.requireNonNull(module);
435 Objects.requireNonNull(name);
436
437 Class<?> caller = Reflection.getCallerClass();
438 if (caller != null && caller.getModule() != module) {
439 // if caller is null, Class.forName is the last java frame on the stack.
440 // java.base has all permissions
441 SecurityManager sm = System.getSecurityManager();
442 if (sm != null) {
443 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
444 }
445 }
446
447 PrivilegedAction<ClassLoader> pa = module::getClassLoader;
448 ClassLoader cl = AccessController.doPrivileged(pa);
449 if (module.isNamed() && cl != null) {
450 return cl.loadLocalClass(module, name);
451 }
452
453 final Class<?> c;
454 if (cl != null) {
455 c = cl.loadLocalClass(name);
456 } else {
457 c = BootLoader.loadClassOrNull(name);
458 }
459
460 if (c != null && c.getModule() == module) {
461 return c;
462 } else {
463 return null;
464 }
465 }
466
J. Duke319a3b92007-12-01 00:00:00 +0000467 /**
468 * Creates a new instance of the class represented by this {@code Class}
469 * object. The class is instantiated as if by a {@code new}
470 * expression with an empty argument list. The class is initialized if it
471 * has not already been initialized.
472 *
473 * <p>Note that this method propagates any exception thrown by the
474 * nullary constructor, including a checked exception. Use of
475 * this method effectively bypasses the compile-time exception
476 * checking that would otherwise be performed by the compiler.
477 * The {@link
478 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
479 * Constructor.newInstance} method avoids this problem by wrapping
480 * any exception thrown by the constructor in a (checked) {@link
481 * java.lang.reflect.InvocationTargetException}.
482 *
Mandy Chung5a360a72013-07-02 15:58:09 -0700483 * @return a newly allocated instance of the class represented by this
484 * object.
485 * @throws IllegalAccessException if the class or its nullary
486 * constructor is not accessible.
487 * @throws InstantiationException
488 * if this {@code Class} represents an abstract class,
489 * an interface, an array class, a primitive type, or void;
490 * or if the class has no nullary constructor;
491 * or if the instantiation fails for some other reason.
492 * @throws ExceptionInInitializerError if the initialization
493 * provoked by this method fails.
494 * @throws SecurityException
495 * If a security manager, <i>s</i>, is present and
496 * the caller's class loader is not the same as or an
497 * ancestor of the class loader for the current class and
498 * invocation of {@link SecurityManager#checkPackageAccess
499 * s.checkPackageAccess()} denies access to the package
500 * of this class.
J. Duke319a3b92007-12-01 00:00:00 +0000501 */
Mandy Chung176ed8d2013-04-16 21:39:52 -0700502 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +0000503 public T newInstance()
504 throws InstantiationException, IllegalAccessException
505 {
506 if (System.getSecurityManager() != null) {
Mandy Chung176ed8d2013-04-16 21:39:52 -0700507 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
J. Duke319a3b92007-12-01 00:00:00 +0000508 }
J. Duke319a3b92007-12-01 00:00:00 +0000509
J. Duke319a3b92007-12-01 00:00:00 +0000510 // NOTE: the following code may not be strictly correct under
511 // the current Java memory model.
512
513 // Constructor lookup
514 if (cachedConstructor == null) {
515 if (this == Class.class) {
516 throw new IllegalAccessException(
517 "Can not call newInstance() on the Class for java.lang.Class"
518 );
519 }
520 try {
Joe Darcybd9e7da2009-10-06 13:31:41 -0700521 Class<?>[] empty = {};
J. Duke319a3b92007-12-01 00:00:00 +0000522 final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
523 // Disable accessibility checks on the constructor
524 // since we have to do the security check here anyway
525 // (the stack depth is wrong for the Constructor's
526 // security check to work)
Martin Buchholz43410942008-03-10 15:07:09 -0700527 java.security.AccessController.doPrivileged(
Joe Darcyd1122152015-04-23 09:32:35 -0700528 new java.security.PrivilegedAction<>() {
Martin Buchholz43410942008-03-10 15:07:09 -0700529 public Void run() {
J. Duke319a3b92007-12-01 00:00:00 +0000530 c.setAccessible(true);
531 return null;
532 }
533 });
534 cachedConstructor = c;
535 } catch (NoSuchMethodException e) {
Joe Darcy2aa1b6d2011-08-08 09:07:43 -0700536 throw (InstantiationException)
537 new InstantiationException(getName()).initCause(e);
J. Duke319a3b92007-12-01 00:00:00 +0000538 }
539 }
540 Constructor<T> tmpConstructor = cachedConstructor;
541 // Security check (same as in java.lang.reflect.Constructor)
Alan Batemandb4d3832016-03-17 19:04:16 +0000542 Class<?> caller = Reflection.getCallerClass();
543 if (newInstanceCallerCache != caller) {
544 int modifiers = tmpConstructor.getModifiers();
545 Reflection.ensureMemberAccess(caller, this, null, modifiers);
546 newInstanceCallerCache = caller;
J. Duke319a3b92007-12-01 00:00:00 +0000547 }
548 // Run constructor
549 try {
550 return tmpConstructor.newInstance((Object[])null);
551 } catch (InvocationTargetException e) {
552 Unsafe.getUnsafe().throwException(e.getTargetException());
553 // Not reached
554 return null;
555 }
556 }
Martin Buchholza2f0fe32015-09-15 21:56:04 -0700557 private transient volatile Constructor<T> cachedConstructor;
558 private transient volatile Class<?> newInstanceCallerCache;
J. Duke319a3b92007-12-01 00:00:00 +0000559
560
561 /**
562 * Determines if the specified {@code Object} is assignment-compatible
563 * with the object represented by this {@code Class}. This method is
564 * the dynamic equivalent of the Java language {@code instanceof}
565 * operator. The method returns {@code true} if the specified
566 * {@code Object} argument is non-null and can be cast to the
567 * reference type represented by this {@code Class} object without
568 * raising a {@code ClassCastException.} It returns {@code false}
569 * otherwise.
570 *
571 * <p> Specifically, if this {@code Class} object represents a
572 * declared class, this method returns {@code true} if the specified
573 * {@code Object} argument is an instance of the represented class (or
574 * of any of its subclasses); it returns {@code false} otherwise. If
575 * this {@code Class} object represents an array class, this method
576 * returns {@code true} if the specified {@code Object} argument
577 * can be converted to an object of the array class by an identity
578 * conversion or by a widening reference conversion; it returns
579 * {@code false} otherwise. If this {@code Class} object
580 * represents an interface, this method returns {@code true} if the
581 * class or any superclass of the specified {@code Object} argument
582 * implements this interface; it returns {@code false} otherwise. If
583 * this {@code Class} object represents a primitive type, this method
584 * returns {@code false}.
585 *
586 * @param obj the object to check
587 * @return true if {@code obj} is an instance of this class
588 *
Henry Jenea9a7a82014-06-10 16:18:54 -0700589 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +0000590 */
Zoltan Majo94d36642015-07-03 07:23:45 +0200591 @HotSpotIntrinsicCandidate
J. Duke319a3b92007-12-01 00:00:00 +0000592 public native boolean isInstance(Object obj);
593
594
595 /**
596 * Determines if the class or interface represented by this
597 * {@code Class} object is either the same as, or is a superclass or
598 * superinterface of, the class or interface represented by the specified
599 * {@code Class} parameter. It returns {@code true} if so;
600 * otherwise it returns {@code false}. If this {@code Class}
601 * object represents a primitive type, this method returns
602 * {@code true} if the specified {@code Class} parameter is
603 * exactly this {@code Class} object; otherwise it returns
604 * {@code false}.
605 *
606 * <p> Specifically, this method tests whether the type represented by the
607 * specified {@code Class} parameter can be converted to the type
608 * represented by this {@code Class} object via an identity conversion
609 * or via a widening reference conversion. See <em>The Java Language
610 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
611 *
612 * @param cls the {@code Class} object to be checked
613 * @return the {@code boolean} value indicating whether objects of the
614 * type {@code cls} can be assigned to objects of this class
615 * @exception NullPointerException if the specified Class parameter is
616 * null.
Henry Jenea9a7a82014-06-10 16:18:54 -0700617 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +0000618 */
Zoltan Majo94d36642015-07-03 07:23:45 +0200619 @HotSpotIntrinsicCandidate
J. Duke319a3b92007-12-01 00:00:00 +0000620 public native boolean isAssignableFrom(Class<?> cls);
621
622
623 /**
624 * Determines if the specified {@code Class} object represents an
625 * interface type.
626 *
627 * @return {@code true} if this object represents an interface;
628 * {@code false} otherwise.
629 */
Zoltan Majo94d36642015-07-03 07:23:45 +0200630 @HotSpotIntrinsicCandidate
J. Duke319a3b92007-12-01 00:00:00 +0000631 public native boolean isInterface();
632
633
634 /**
635 * Determines if this {@code Class} object represents an array class.
636 *
637 * @return {@code true} if this object represents an array class;
638 * {@code false} otherwise.
Henry Jenea9a7a82014-06-10 16:18:54 -0700639 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +0000640 */
Zoltan Majo94d36642015-07-03 07:23:45 +0200641 @HotSpotIntrinsicCandidate
J. Duke319a3b92007-12-01 00:00:00 +0000642 public native boolean isArray();
643
644
645 /**
646 * Determines if the specified {@code Class} object represents a
647 * primitive type.
648 *
649 * <p> There are nine predefined {@code Class} objects to represent
650 * the eight primitive types and void. These are created by the Java
651 * Virtual Machine, and have the same names as the primitive types that
652 * they represent, namely {@code boolean}, {@code byte},
653 * {@code char}, {@code short}, {@code int},
654 * {@code long}, {@code float}, and {@code double}.
655 *
656 * <p> These objects may only be accessed via the following public static
657 * final variables, and are the only {@code Class} objects for which
658 * this method returns {@code true}.
659 *
660 * @return true if and only if this class represents a primitive type
661 *
662 * @see java.lang.Boolean#TYPE
663 * @see java.lang.Character#TYPE
664 * @see java.lang.Byte#TYPE
665 * @see java.lang.Short#TYPE
666 * @see java.lang.Integer#TYPE
667 * @see java.lang.Long#TYPE
668 * @see java.lang.Float#TYPE
669 * @see java.lang.Double#TYPE
670 * @see java.lang.Void#TYPE
Henry Jenea9a7a82014-06-10 16:18:54 -0700671 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +0000672 */
Zoltan Majo94d36642015-07-03 07:23:45 +0200673 @HotSpotIntrinsicCandidate
J. Duke319a3b92007-12-01 00:00:00 +0000674 public native boolean isPrimitive();
675
676 /**
677 * Returns true if this {@code Class} object represents an annotation
678 * type. Note that if this method returns true, {@link #isInterface()}
679 * would also return true, as all annotation types are also interfaces.
680 *
681 * @return {@code true} if this class object represents an annotation
682 * type; {@code false} otherwise
683 * @since 1.5
684 */
685 public boolean isAnnotation() {
686 return (getModifiers() & ANNOTATION) != 0;
687 }
688
689 /**
690 * Returns {@code true} if this class is a synthetic class;
691 * returns {@code false} otherwise.
692 * @return {@code true} if and only if this class is a synthetic class as
693 * defined by the Java Language Specification.
Joe Darcy059b2b62012-12-19 11:53:52 -0800694 * @jls 13.1 The Form of a Binary
J. Duke319a3b92007-12-01 00:00:00 +0000695 * @since 1.5
696 */
697 public boolean isSynthetic() {
698 return (getModifiers() & SYNTHETIC) != 0;
699 }
700
701 /**
702 * Returns the name of the entity (class, interface, array class,
703 * primitive type, or void) represented by this {@code Class} object,
704 * as a {@code String}.
705 *
706 * <p> If this class object represents a reference type that is not an
707 * array type then the binary name of the class is returned, as specified
Jim Holmlundbbf16c02011-04-13 12:16:13 -0700708 * by
709 * <cite>The Java&trade; Language Specification</cite>.
J. Duke319a3b92007-12-01 00:00:00 +0000710 *
711 * <p> If this class object represents a primitive type or void, then the
712 * name returned is a {@code String} equal to the Java language
713 * keyword corresponding to the primitive type or void.
714 *
715 * <p> If this class object represents a class of arrays, then the internal
716 * form of the name consists of the name of the element type preceded by
717 * one or more '{@code [}' characters representing the depth of the array
718 * nesting. The encoding of element type names is as follows:
719 *
720 * <blockquote><table summary="Element types and encodings">
721 * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
722 * <tr><td> boolean <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
723 * <tr><td> byte <td> &nbsp;&nbsp;&nbsp; <td align=center> B
724 * <tr><td> char <td> &nbsp;&nbsp;&nbsp; <td align=center> C
725 * <tr><td> class or interface
726 * <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
727 * <tr><td> double <td> &nbsp;&nbsp;&nbsp; <td align=center> D
728 * <tr><td> float <td> &nbsp;&nbsp;&nbsp; <td align=center> F
729 * <tr><td> int <td> &nbsp;&nbsp;&nbsp; <td align=center> I
730 * <tr><td> long <td> &nbsp;&nbsp;&nbsp; <td align=center> J
731 * <tr><td> short <td> &nbsp;&nbsp;&nbsp; <td align=center> S
732 * </table></blockquote>
733 *
734 * <p> The class or interface name <i>classname</i> is the binary name of
735 * the class specified above.
736 *
737 * <p> Examples:
738 * <blockquote><pre>
739 * String.class.getName()
740 * returns "java.lang.String"
741 * byte.class.getName()
742 * returns "byte"
743 * (new Object[3]).getClass().getName()
744 * returns "[Ljava.lang.Object;"
745 * (new int[3][4][5][6][7][8][9]).getClass().getName()
746 * returns "[[[[[[[I"
747 * </pre></blockquote>
748 *
749 * @return the name of the class or interface
750 * represented by this object.
751 */
752 public String getName() {
Martin Buchholzb5f1c842009-09-12 15:30:13 -0700753 String name = this.name;
J. Duke319a3b92007-12-01 00:00:00 +0000754 if (name == null)
Martin Buchholzb5f1c842009-09-12 15:30:13 -0700755 this.name = name = getName0();
J. Duke319a3b92007-12-01 00:00:00 +0000756 return name;
757 }
758
759 // cache the name to reduce the number of calls into the VM
760 private transient String name;
761 private native String getName0();
762
763 /**
764 * Returns the class loader for the class. Some implementations may use
765 * null to represent the bootstrap class loader. This method will return
766 * null in such implementations if this class was loaded by the bootstrap
767 * class loader.
768 *
769 * <p> If a security manager is present, and the caller's class loader is
770 * not null and the caller's class loader is not the same as or an ancestor of
771 * the class loader for the class whose class loader is requested, then
772 * this method calls the security manager's {@code checkPermission}
773 * method with a {@code RuntimePermission("getClassLoader")}
774 * permission to ensure it's ok to access the class loader for the class.
775 *
776 * <p>If this object
777 * represents a primitive type or void, null is returned.
778 *
779 * @return the class loader that loaded the class or interface
780 * represented by this object.
781 * @throws SecurityException
782 * if a security manager exists and its
783 * {@code checkPermission} method denies
784 * access to the class loader for the class.
785 * @see java.lang.ClassLoader
786 * @see SecurityManager#checkPermission
787 * @see java.lang.RuntimePermission
788 */
Mandy Chung176ed8d2013-04-16 21:39:52 -0700789 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +0000790 public ClassLoader getClassLoader() {
791 ClassLoader cl = getClassLoader0();
792 if (cl == null)
793 return null;
794 SecurityManager sm = System.getSecurityManager();
795 if (sm != null) {
Mandy Chung176ed8d2013-04-16 21:39:52 -0700796 ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
J. Duke319a3b92007-12-01 00:00:00 +0000797 }
798 return cl;
799 }
800
801 // Package-private to allow ClassLoader access
Coleen Phillimoreaa12c8f2014-06-24 11:23:34 -0400802 ClassLoader getClassLoader0() { return classLoader; }
J. Duke319a3b92007-12-01 00:00:00 +0000803
Alan Batemandb4d3832016-03-17 19:04:16 +0000804 /**
805 * Returns the module that this class or interface is a member of.
806 *
807 * If this class represents an array type then this method returns the
808 * {@code Module} for the element type. If this class represents a
809 * primitive type or void, then the {@code Module} object for the
810 * {@code java.base} module is returned.
811 *
812 * If this class is in an unnamed module then the {@link
813 * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
814 * loader for this class is returned.
815 *
816 * @return the module that this class or interface is a member of
817 *
818 * @since 9
819 */
820 public Module getModule() {
821 return module;
822 }
823
824 // set by VM
825 private transient Module module;
826
Coleen Phillimoreaa12c8f2014-06-24 11:23:34 -0400827 // Initialized in JVM not by private constructor
Daniel Fuchs3034f052014-12-01 21:02:21 +0100828 // This field is filtered from reflection access, i.e. getDeclaredField
829 // will throw NoSuchFieldException
Coleen Phillimoreaa12c8f2014-06-24 11:23:34 -0400830 private final ClassLoader classLoader;
J. Duke319a3b92007-12-01 00:00:00 +0000831
832 /**
833 * Returns an array of {@code TypeVariable} objects that represent the
834 * type variables declared by the generic declaration represented by this
835 * {@code GenericDeclaration} object, in declaration order. Returns an
836 * array of length 0 if the underlying generic declaration declares no type
837 * variables.
838 *
839 * @return an array of {@code TypeVariable} objects that represent
840 * the type variables declared by this generic declaration
Joe Darcy21aa3652009-07-07 16:12:34 -0700841 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
J. Duke319a3b92007-12-01 00:00:00 +0000842 * signature of this generic declaration does not conform to
Jim Holmlundbbf16c02011-04-13 12:16:13 -0700843 * the format specified in
844 * <cite>The Java&trade; Virtual Machine Specification</cite>
J. Duke319a3b92007-12-01 00:00:00 +0000845 * @since 1.5
846 */
Omair Majidd312aad2011-12-08 13:48:54 -0500847 @SuppressWarnings("unchecked")
J. Duke319a3b92007-12-01 00:00:00 +0000848 public TypeVariable<Class<T>>[] getTypeParameters() {
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +0400849 ClassRepository info = getGenericInfo();
850 if (info != null)
851 return (TypeVariable<Class<T>>[])info.getTypeParameters();
J. Duke319a3b92007-12-01 00:00:00 +0000852 else
Joe Darcybd9e7da2009-10-06 13:31:41 -0700853 return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
J. Duke319a3b92007-12-01 00:00:00 +0000854 }
855
856
857 /**
Martin Buchholz8ecf7072014-11-06 13:29:36 -0800858 * Returns the {@code Class} representing the direct superclass of the
859 * entity (class, interface, primitive type or void) represented by
860 * this {@code Class}. If this {@code Class} represents either the
J. Duke319a3b92007-12-01 00:00:00 +0000861 * {@code Object} class, an interface, a primitive type, or void, then
862 * null is returned. If this object represents an array class then the
863 * {@code Class} object representing the {@code Object} class is
864 * returned.
865 *
Martin Buchholz8ecf7072014-11-06 13:29:36 -0800866 * @return the direct superclass of the class represented by this object
J. Duke319a3b92007-12-01 00:00:00 +0000867 */
Zoltan Majo94d36642015-07-03 07:23:45 +0200868 @HotSpotIntrinsicCandidate
J. Duke319a3b92007-12-01 00:00:00 +0000869 public native Class<? super T> getSuperclass();
870
871
872 /**
873 * Returns the {@code Type} representing the direct superclass of
874 * the entity (class, interface, primitive type or void) represented by
875 * this {@code Class}.
876 *
877 * <p>If the superclass is a parameterized type, the {@code Type}
878 * object returned must accurately reflect the actual type
879 * parameters used in the source code. The parameterized type
880 * representing the superclass is created if it had not been
881 * created before. See the declaration of {@link
882 * java.lang.reflect.ParameterizedType ParameterizedType} for the
883 * semantics of the creation process for parameterized types. If
884 * this {@code Class} represents either the {@code Object}
885 * class, an interface, a primitive type, or void, then null is
886 * returned. If this object represents an array class then the
887 * {@code Class} object representing the {@code Object} class is
888 * returned.
889 *
Joe Darcy21aa3652009-07-07 16:12:34 -0700890 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
Jim Holmlundbbf16c02011-04-13 12:16:13 -0700891 * class signature does not conform to the format specified in
892 * <cite>The Java&trade; Virtual Machine Specification</cite>
J. Duke319a3b92007-12-01 00:00:00 +0000893 * @throws TypeNotPresentException if the generic superclass
894 * refers to a non-existent type declaration
Joe Darcy21aa3652009-07-07 16:12:34 -0700895 * @throws java.lang.reflect.MalformedParameterizedTypeException if the
J. Duke319a3b92007-12-01 00:00:00 +0000896 * generic superclass refers to a parameterized type that cannot be
897 * instantiated for any reason
Martin Buchholz8ecf7072014-11-06 13:29:36 -0800898 * @return the direct superclass of the class represented by this object
J. Duke319a3b92007-12-01 00:00:00 +0000899 * @since 1.5
900 */
901 public Type getGenericSuperclass() {
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +0400902 ClassRepository info = getGenericInfo();
903 if (info == null) {
J. Duke319a3b92007-12-01 00:00:00 +0000904 return getSuperclass();
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +0400905 }
906
907 // Historical irregularity:
908 // Generic signature marks interfaces with superclass = Object
909 // but this API returns null for interfaces
910 if (isInterface()) {
911 return null;
912 }
913
914 return info.getSuperclass();
J. Duke319a3b92007-12-01 00:00:00 +0000915 }
916
917 /**
Alan Batemandb4d3832016-03-17 19:04:16 +0000918 * Gets the package of this class.
J. Duke319a3b92007-12-01 00:00:00 +0000919 *
Alan Batemandb4d3832016-03-17 19:04:16 +0000920 * <p>If this class represents an array type, a primitive type or void,
921 * this method returns {@code null}.
J. Duke319a3b92007-12-01 00:00:00 +0000922 *
Alan Batemandb4d3832016-03-17 19:04:16 +0000923 * @return the package of this class.
J. Duke319a3b92007-12-01 00:00:00 +0000924 */
925 public Package getPackage() {
Alan Batemandb4d3832016-03-17 19:04:16 +0000926 if (isPrimitive() || isArray()) {
927 return null;
928 }
929 ClassLoader cl = getClassLoader0();
930 return cl != null ? cl.definePackage(this)
931 : BootLoader.definePackage(this);
J. Duke319a3b92007-12-01 00:00:00 +0000932 }
933
Alan Batemandb4d3832016-03-17 19:04:16 +0000934 /**
935 * Returns the fully qualified package name.
936 *
937 * <p> If this class is a top level class, then this method returns the fully
938 * qualified name of the package that the class is a member of, or the
939 * empty string if the class is in an unnamed package.
940 *
941 * <p> If this class is a member class, then this method is equivalent to
942 * invoking {@code getPackageName()} on the {@link #getEnclosingClass
943 * enclosing class}.
944 *
945 * <p> If this class is a {@link #isLocalClass local class} or an {@link
946 * #isAnonymousClass() anonymous class}, then this method is equivalent to
947 * invoking {@code getPackageName()} on the {@link #getDeclaringClass
948 * declaring class} of the {@link #getEnclosingMethod enclosing method} or
949 * {@link #getEnclosingConstructor enclosing constructor}.
950 *
951 * <p> This method returns {@code null} if this class represents an array type,
952 * a primitive type or void.
953 *
954 * @return the fully qualified package name
955 *
956 * @since 9
957 * @jls 6.7 Fully Qualified Names
958 */
959 public String getPackageName() {
960 String pn = this.packageName;
961 if (pn == null && !isArray() && !isPrimitive()) {
962 String cn = getName();
963 int dot = cn.lastIndexOf('.');
964 pn = (dot != -1) ? cn.substring(0, dot).intern() : "";
965 this.packageName = pn;
966 }
967 return pn;
968 }
969
970 // cached package name
971 private String packageName;
J. Duke319a3b92007-12-01 00:00:00 +0000972
973 /**
Martin Buchholz8ecf7072014-11-06 13:29:36 -0800974 * Returns the interfaces directly implemented by the class or interface
J. Duke319a3b92007-12-01 00:00:00 +0000975 * represented by this object.
976 *
Martin Buchholz8ecf7072014-11-06 13:29:36 -0800977 * <p>If this object represents a class, the return value is an array
978 * containing objects representing all interfaces directly implemented by
979 * the class. The order of the interface objects in the array corresponds
980 * to the order of the interface names in the {@code implements} clause of
981 * the declaration of the class represented by this object. For example,
982 * given the declaration:
J. Duke319a3b92007-12-01 00:00:00 +0000983 * <blockquote>
984 * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
985 * </blockquote>
986 * suppose the value of {@code s} is an instance of
987 * {@code Shimmer}; the value of the expression:
988 * <blockquote>
989 * {@code s.getClass().getInterfaces()[0]}
990 * </blockquote>
991 * is the {@code Class} object that represents interface
992 * {@code FloorWax}; and the value of:
993 * <blockquote>
994 * {@code s.getClass().getInterfaces()[1]}
995 * </blockquote>
996 * is the {@code Class} object that represents interface
997 * {@code DessertTopping}.
998 *
Martin Buchholz8ecf7072014-11-06 13:29:36 -0800999 * <p>If this object represents an interface, the array contains objects
1000 * representing all interfaces directly extended by the interface. The
1001 * order of the interface objects in the array corresponds to the order of
1002 * the interface names in the {@code extends} clause of the declaration of
1003 * the interface represented by this object.
J. Duke319a3b92007-12-01 00:00:00 +00001004 *
Martin Buchholz8ecf7072014-11-06 13:29:36 -08001005 * <p>If this object represents a class or interface that implements no
J. Duke319a3b92007-12-01 00:00:00 +00001006 * interfaces, the method returns an array of length 0.
1007 *
Martin Buchholz8ecf7072014-11-06 13:29:36 -08001008 * <p>If this object represents a primitive type or void, the method
J. Duke319a3b92007-12-01 00:00:00 +00001009 * returns an array of length 0.
1010 *
Martin Buchholz8ecf7072014-11-06 13:29:36 -08001011 * <p>If this {@code Class} object represents an array type, the
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001012 * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1013 * returned in that order.
1014 *
Martin Buchholz8ecf7072014-11-06 13:29:36 -08001015 * @return an array of interfaces directly implemented by this class
J. Duke319a3b92007-12-01 00:00:00 +00001016 */
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +04001017 public Class<?>[] getInterfaces() {
1018 ReflectionData<T> rd = reflectionData();
1019 if (rd == null) {
1020 // no cloning required
1021 return getInterfaces0();
1022 } else {
1023 Class<?>[] interfaces = rd.interfaces;
1024 if (interfaces == null) {
1025 interfaces = getInterfaces0();
1026 rd.interfaces = interfaces;
1027 }
1028 // defensively copy before handing over to user code
1029 return interfaces.clone();
1030 }
1031 }
1032
1033 private native Class<?>[] getInterfaces0();
J. Duke319a3b92007-12-01 00:00:00 +00001034
1035 /**
1036 * Returns the {@code Type}s representing the interfaces
1037 * directly implemented by the class or interface represented by
1038 * this object.
1039 *
1040 * <p>If a superinterface is a parameterized type, the
1041 * {@code Type} object returned for it must accurately reflect
1042 * the actual type parameters used in the source code. The
1043 * parameterized type representing each superinterface is created
1044 * if it had not been created before. See the declaration of
1045 * {@link java.lang.reflect.ParameterizedType ParameterizedType}
1046 * for the semantics of the creation process for parameterized
1047 * types.
1048 *
Martin Buchholz8ecf7072014-11-06 13:29:36 -08001049 * <p>If this object represents a class, the return value is an array
1050 * containing objects representing all interfaces directly implemented by
1051 * the class. The order of the interface objects in the array corresponds
1052 * to the order of the interface names in the {@code implements} clause of
1053 * the declaration of the class represented by this object.
1054 *
1055 * <p>If this object represents an interface, the array contains objects
1056 * representing all interfaces directly extended by the interface. The
1057 * order of the interface objects in the array corresponds to the order of
1058 * the interface names in the {@code extends} clause of the declaration of
1059 * the interface represented by this object.
1060 *
1061 * <p>If this object represents a class or interface that implements no
1062 * interfaces, the method returns an array of length 0.
1063 *
1064 * <p>If this object represents a primitive type or void, the method
1065 * returns an array of length 0.
1066 *
1067 * <p>If this {@code Class} object represents an array type, the
1068 * interfaces {@code Cloneable} and {@code java.io.Serializable} are
J. Duke319a3b92007-12-01 00:00:00 +00001069 * returned in that order.
1070 *
Joe Darcy21aa3652009-07-07 16:12:34 -07001071 * @throws java.lang.reflect.GenericSignatureFormatError
J. Duke319a3b92007-12-01 00:00:00 +00001072 * if the generic class signature does not conform to the format
Jim Holmlundbbf16c02011-04-13 12:16:13 -07001073 * specified in
1074 * <cite>The Java&trade; Virtual Machine Specification</cite>
J. Duke319a3b92007-12-01 00:00:00 +00001075 * @throws TypeNotPresentException if any of the generic
1076 * superinterfaces refers to a non-existent type declaration
Joe Darcy21aa3652009-07-07 16:12:34 -07001077 * @throws java.lang.reflect.MalformedParameterizedTypeException
1078 * if any of the generic superinterfaces refer to a parameterized
1079 * type that cannot be instantiated for any reason
Martin Buchholz8ecf7072014-11-06 13:29:36 -08001080 * @return an array of interfaces directly implemented by this class
J. Duke319a3b92007-12-01 00:00:00 +00001081 * @since 1.5
1082 */
1083 public Type[] getGenericInterfaces() {
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +04001084 ClassRepository info = getGenericInfo();
1085 return (info == null) ? getInterfaces() : info.getSuperInterfaces();
J. Duke319a3b92007-12-01 00:00:00 +00001086 }
1087
1088
1089 /**
1090 * Returns the {@code Class} representing the component type of an
1091 * array. If this class does not represent an array class this method
1092 * returns null.
1093 *
1094 * @return the {@code Class} representing the component type of this
1095 * class if this class is an array
1096 * @see java.lang.reflect.Array
Henry Jenea9a7a82014-06-10 16:18:54 -07001097 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00001098 */
Coleen Phillimorecbb6f302014-07-02 16:47:49 -04001099 public Class<?> getComponentType() {
1100 // Only return for array types. Storage may be reused for Class for instance types.
1101 if (isArray()) {
1102 return componentType;
1103 } else {
1104 return null;
1105 }
1106 }
1107
1108 private final Class<?> componentType;
J. Duke319a3b92007-12-01 00:00:00 +00001109
1110
1111 /**
1112 * Returns the Java language modifiers for this class or interface, encoded
1113 * in an integer. The modifiers consist of the Java Virtual Machine's
1114 * constants for {@code public}, {@code protected},
1115 * {@code private}, {@code final}, {@code static},
1116 * {@code abstract} and {@code interface}; they should be decoded
1117 * using the methods of class {@code Modifier}.
1118 *
1119 * <p> If the underlying class is an array class, then its
1120 * {@code public}, {@code private} and {@code protected}
1121 * modifiers are the same as those of its component type. If this
1122 * {@code Class} represents a primitive type or void, its
1123 * {@code public} modifier is always {@code true}, and its
1124 * {@code protected} and {@code private} modifiers are always
1125 * {@code false}. If this object represents an array class, a
1126 * primitive type or void, then its {@code final} modifier is always
1127 * {@code true} and its interface modifier is always
1128 * {@code false}. The values of its other modifiers are not determined
1129 * by this specification.
1130 *
1131 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
1132 * Specification</em>, table 4.1.
1133 *
1134 * @return the {@code int} representing the modifiers for this class
1135 * @see java.lang.reflect.Modifier
Henry Jenea9a7a82014-06-10 16:18:54 -07001136 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00001137 */
Zoltan Majo94d36642015-07-03 07:23:45 +02001138 @HotSpotIntrinsicCandidate
J. Duke319a3b92007-12-01 00:00:00 +00001139 public native int getModifiers();
1140
1141
1142 /**
1143 * Gets the signers of this class.
1144 *
1145 * @return the signers of this class, or null if there are no signers. In
1146 * particular, this method returns null if this object represents
1147 * a primitive type or void.
Henry Jenea9a7a82014-06-10 16:18:54 -07001148 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00001149 */
1150 public native Object[] getSigners();
1151
1152
1153 /**
1154 * Set the signers of this class.
1155 */
1156 native void setSigners(Object[] signers);
1157
1158
1159 /**
1160 * If this {@code Class} object represents a local or anonymous
1161 * class within a method, returns a {@link
1162 * java.lang.reflect.Method Method} object representing the
1163 * immediately enclosing method of the underlying class. Returns
1164 * {@code null} otherwise.
1165 *
1166 * In particular, this method returns {@code null} if the underlying
1167 * class is a local or anonymous class immediately enclosed by a type
1168 * declaration, instance initializer or static initializer.
1169 *
1170 * @return the immediately enclosing method of the underlying class, if
1171 * that class is a local or anonymous class; otherwise {@code null}.
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001172 *
Mandy Chung5a360a72013-07-02 15:58:09 -07001173 * @throws SecurityException
1174 * If a security manager, <i>s</i>, is present and any of the
1175 * following conditions is met:
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001176 *
Mandy Chung5a360a72013-07-02 15:58:09 -07001177 * <ul>
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001178 *
Mandy Chung5a360a72013-07-02 15:58:09 -07001179 * <li> the caller's class loader is not the same as the
1180 * class loader of the enclosing class and invocation of
1181 * {@link SecurityManager#checkPermission
1182 * s.checkPermission} method with
1183 * {@code RuntimePermission("accessDeclaredMembers")}
1184 * denies access to the methods within the enclosing class
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001185 *
Mandy Chung5a360a72013-07-02 15:58:09 -07001186 * <li> the caller's class loader is not the same as or an
1187 * ancestor of the class loader for the enclosing class and
1188 * invocation of {@link SecurityManager#checkPackageAccess
1189 * s.checkPackageAccess()} denies access to the package
1190 * of the enclosing class
1191 *
1192 * </ul>
J. Duke319a3b92007-12-01 00:00:00 +00001193 * @since 1.5
1194 */
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001195 @CallerSensitive
1196 public Method getEnclosingMethod() throws SecurityException {
J. Duke319a3b92007-12-01 00:00:00 +00001197 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1198
1199 if (enclosingInfo == null)
1200 return null;
1201 else {
1202 if (!enclosingInfo.isMethod())
1203 return null;
1204
1205 MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
1206 getFactory());
Joe Darcybd9e7da2009-10-06 13:31:41 -07001207 Class<?> returnType = toClass(typeInfo.getReturnType());
J. Duke319a3b92007-12-01 00:00:00 +00001208 Type [] parameterTypes = typeInfo.getParameterTypes();
1209 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1210
1211 // Convert Types to Classes; returned types *should*
1212 // be class objects since the methodDescriptor's used
1213 // don't have generics information
1214 for(int i = 0; i < parameterClasses.length; i++)
1215 parameterClasses[i] = toClass(parameterTypes[i]);
1216
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001217 // Perform access check
Joel Borggrén-Franckcdf8c272015-02-25 14:30:02 +01001218 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001219 enclosingCandidate.checkMemberAccess(Member.DECLARED,
1220 Reflection.getCallerClass(), true);
Joel Borggrén-Franckcdf8c272015-02-25 14:30:02 +01001221 // Client is ok to access declared methods but j.l.Class might not be.
1222 Method[] candidates = AccessController.doPrivileged(
Joe Darcyd1122152015-04-23 09:32:35 -07001223 new PrivilegedAction<>() {
Joel Borggrén-Franckcdf8c272015-02-25 14:30:02 +01001224 @Override
1225 public Method[] run() {
1226 return enclosingCandidate.getDeclaredMethods();
1227 }
1228 });
J. Duke319a3b92007-12-01 00:00:00 +00001229 /*
1230 * Loop over all declared methods; match method name,
1231 * number of and type of parameters, *and* return
1232 * type. Matching return type is also necessary
1233 * because of covariant returns, etc.
1234 */
Joel Borggrén-Franckcdf8c272015-02-25 14:30:02 +01001235 for(Method m: candidates) {
J. Duke319a3b92007-12-01 00:00:00 +00001236 if (m.getName().equals(enclosingInfo.getName()) ) {
1237 Class<?>[] candidateParamClasses = m.getParameterTypes();
1238 if (candidateParamClasses.length == parameterClasses.length) {
1239 boolean matches = true;
1240 for(int i = 0; i < candidateParamClasses.length; i++) {
1241 if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1242 matches = false;
1243 break;
1244 }
1245 }
1246
1247 if (matches) { // finally, check return type
1248 if (m.getReturnType().equals(returnType) )
1249 return m;
1250 }
1251 }
1252 }
1253 }
1254
1255 throw new InternalError("Enclosing method not found");
1256 }
1257 }
1258
1259 private native Object[] getEnclosingMethod0();
1260
1261 private EnclosingMethodInfo getEnclosingMethodInfo() {
1262 Object[] enclosingInfo = getEnclosingMethod0();
1263 if (enclosingInfo == null)
1264 return null;
1265 else {
1266 return new EnclosingMethodInfo(enclosingInfo);
1267 }
1268 }
1269
Martin Buchholza2f0fe32015-09-15 21:56:04 -07001270 private static final class EnclosingMethodInfo {
J. Duke319a3b92007-12-01 00:00:00 +00001271 private Class<?> enclosingClass;
1272 private String name;
1273 private String descriptor;
1274
1275 private EnclosingMethodInfo(Object[] enclosingInfo) {
1276 if (enclosingInfo.length != 3)
1277 throw new InternalError("Malformed enclosing method information");
1278 try {
1279 // The array is expected to have three elements:
1280
1281 // the immediately enclosing class
1282 enclosingClass = (Class<?>) enclosingInfo[0];
1283 assert(enclosingClass != null);
1284
1285 // the immediately enclosing method or constructor's
1286 // name (can be null).
1287 name = (String) enclosingInfo[1];
1288
1289 // the immediately enclosing method or constructor's
1290 // descriptor (null iff name is).
1291 descriptor = (String) enclosingInfo[2];
1292 assert((name != null && descriptor != null) || name == descriptor);
1293 } catch (ClassCastException cce) {
Sebastian Sickelmann0a9fa0f2011-08-30 11:53:11 -07001294 throw new InternalError("Invalid type in enclosing method information", cce);
J. Duke319a3b92007-12-01 00:00:00 +00001295 }
1296 }
1297
1298 boolean isPartial() {
1299 return enclosingClass == null || name == null || descriptor == null;
1300 }
1301
1302 boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
1303
1304 boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
1305
1306 Class<?> getEnclosingClass() { return enclosingClass; }
1307
1308 String getName() { return name; }
1309
1310 String getDescriptor() { return descriptor; }
1311
1312 }
1313
Joe Darcybd9e7da2009-10-06 13:31:41 -07001314 private static Class<?> toClass(Type o) {
J. Duke319a3b92007-12-01 00:00:00 +00001315 if (o instanceof GenericArrayType)
1316 return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1317 0)
1318 .getClass();
Joe Darcybd9e7da2009-10-06 13:31:41 -07001319 return (Class<?>)o;
J. Duke319a3b92007-12-01 00:00:00 +00001320 }
1321
1322 /**
1323 * If this {@code Class} object represents a local or anonymous
1324 * class within a constructor, returns a {@link
1325 * java.lang.reflect.Constructor Constructor} object representing
1326 * the immediately enclosing constructor of the underlying
1327 * class. Returns {@code null} otherwise. In particular, this
1328 * method returns {@code null} if the underlying class is a local
1329 * or anonymous class immediately enclosed by a type declaration,
1330 * instance initializer or static initializer.
1331 *
1332 * @return the immediately enclosing constructor of the underlying class, if
1333 * that class is a local or anonymous class; otherwise {@code null}.
Mandy Chung5a360a72013-07-02 15:58:09 -07001334 * @throws SecurityException
1335 * If a security manager, <i>s</i>, is present and any of the
1336 * following conditions is met:
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001337 *
Mandy Chung5a360a72013-07-02 15:58:09 -07001338 * <ul>
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001339 *
Mandy Chung5a360a72013-07-02 15:58:09 -07001340 * <li> the caller's class loader is not the same as the
1341 * class loader of the enclosing class and invocation of
1342 * {@link SecurityManager#checkPermission
1343 * s.checkPermission} method with
1344 * {@code RuntimePermission("accessDeclaredMembers")}
1345 * denies access to the constructors within the enclosing class
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001346 *
Mandy Chung5a360a72013-07-02 15:58:09 -07001347 * <li> the caller's class loader is not the same as or an
1348 * ancestor of the class loader for the enclosing class and
1349 * invocation of {@link SecurityManager#checkPackageAccess
1350 * s.checkPackageAccess()} denies access to the package
1351 * of the enclosing class
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001352 *
Mandy Chung5a360a72013-07-02 15:58:09 -07001353 * </ul>
J. Duke319a3b92007-12-01 00:00:00 +00001354 * @since 1.5
1355 */
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001356 @CallerSensitive
1357 public Constructor<?> getEnclosingConstructor() throws SecurityException {
J. Duke319a3b92007-12-01 00:00:00 +00001358 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1359
1360 if (enclosingInfo == null)
1361 return null;
1362 else {
1363 if (!enclosingInfo.isConstructor())
1364 return null;
1365
1366 ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1367 getFactory());
1368 Type [] parameterTypes = typeInfo.getParameterTypes();
1369 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1370
1371 // Convert Types to Classes; returned types *should*
1372 // be class objects since the methodDescriptor's used
1373 // don't have generics information
1374 for(int i = 0; i < parameterClasses.length; i++)
1375 parameterClasses[i] = toClass(parameterTypes[i]);
1376
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001377 // Perform access check
Joel Borggrén-Franckcdf8c272015-02-25 14:30:02 +01001378 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001379 enclosingCandidate.checkMemberAccess(Member.DECLARED,
1380 Reflection.getCallerClass(), true);
Joel Borggrén-Franckcdf8c272015-02-25 14:30:02 +01001381 // Client is ok to access declared methods but j.l.Class might not be.
1382 Constructor<?>[] candidates = AccessController.doPrivileged(
Joe Darcyd1122152015-04-23 09:32:35 -07001383 new PrivilegedAction<>() {
Joel Borggrén-Franckcdf8c272015-02-25 14:30:02 +01001384 @Override
1385 public Constructor<?>[] run() {
1386 return enclosingCandidate.getDeclaredConstructors();
1387 }
1388 });
J. Duke319a3b92007-12-01 00:00:00 +00001389 /*
1390 * Loop over all declared constructors; match number
1391 * of and type of parameters.
1392 */
Joel Borggrén-Franckcdf8c272015-02-25 14:30:02 +01001393 for(Constructor<?> c: candidates) {
J. Duke319a3b92007-12-01 00:00:00 +00001394 Class<?>[] candidateParamClasses = c.getParameterTypes();
1395 if (candidateParamClasses.length == parameterClasses.length) {
1396 boolean matches = true;
1397 for(int i = 0; i < candidateParamClasses.length; i++) {
1398 if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1399 matches = false;
1400 break;
1401 }
1402 }
1403
1404 if (matches)
1405 return c;
1406 }
1407 }
1408
1409 throw new InternalError("Enclosing constructor not found");
1410 }
1411 }
1412
1413
1414 /**
1415 * If the class or interface represented by this {@code Class} object
1416 * is a member of another class, returns the {@code Class} object
1417 * representing the class in which it was declared. This method returns
1418 * null if this class or interface is not a member of any other class. If
1419 * this {@code Class} object represents an array class, a primitive
1420 * type, or void,then this method returns null.
1421 *
1422 * @return the declaring class for this class
Joel Borggrén-Franck79bda232013-07-15 14:44:50 +02001423 * @throws SecurityException
1424 * If a security manager, <i>s</i>, is present and the caller's
1425 * class loader is not the same as or an ancestor of the class
1426 * loader for the declaring class and invocation of {@link
1427 * SecurityManager#checkPackageAccess s.checkPackageAccess()}
1428 * denies access to the package of the declaring class
Henry Jenea9a7a82014-06-10 16:18:54 -07001429 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00001430 */
Joel Borggrén-Franck79bda232013-07-15 14:44:50 +02001431 @CallerSensitive
1432 public Class<?> getDeclaringClass() throws SecurityException {
1433 final Class<?> candidate = getDeclaringClass0();
1434
1435 if (candidate != null)
1436 candidate.checkPackageAccess(
1437 ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1438 return candidate;
1439 }
1440
1441 private native Class<?> getDeclaringClass0();
J. Duke319a3b92007-12-01 00:00:00 +00001442
1443
1444 /**
1445 * Returns the immediately enclosing class of the underlying
1446 * class. If the underlying class is a top level class this
1447 * method returns {@code null}.
1448 * @return the immediately enclosing class of the underlying class
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001449 * @exception SecurityException
1450 * If a security manager, <i>s</i>, is present and the caller's
1451 * class loader is not the same as or an ancestor of the class
1452 * loader for the enclosing class and invocation of {@link
1453 * SecurityManager#checkPackageAccess s.checkPackageAccess()}
1454 * denies access to the package of the enclosing class
J. Duke319a3b92007-12-01 00:00:00 +00001455 * @since 1.5
1456 */
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001457 @CallerSensitive
1458 public Class<?> getEnclosingClass() throws SecurityException {
J. Duke319a3b92007-12-01 00:00:00 +00001459 // There are five kinds of classes (or interfaces):
1460 // a) Top level classes
1461 // b) Nested classes (static member classes)
1462 // c) Inner classes (non-static member classes)
1463 // d) Local classes (named classes declared within a method)
1464 // e) Anonymous classes
1465
1466
Vladimir Ivanov40973932015-04-14 18:03:12 +03001467 // JVM Spec 4.7.7: A class must have an EnclosingMethod
J. Duke319a3b92007-12-01 00:00:00 +00001468 // attribute if and only if it is a local class or an
1469 // anonymous class.
1470 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001471 Class<?> enclosingCandidate;
J. Duke319a3b92007-12-01 00:00:00 +00001472
1473 if (enclosingInfo == null) {
1474 // This is a top level or a nested class or an inner class (a, b, or c)
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001475 enclosingCandidate = getDeclaringClass();
J. Duke319a3b92007-12-01 00:00:00 +00001476 } else {
1477 Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1478 // This is a local class or an anonymous class (d or e)
1479 if (enclosingClass == this || enclosingClass == null)
1480 throw new InternalError("Malformed enclosing method information");
1481 else
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001482 enclosingCandidate = enclosingClass;
J. Duke319a3b92007-12-01 00:00:00 +00001483 }
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001484
Joel Borggrén-Francka638aed2013-05-07 13:23:08 +02001485 if (enclosingCandidate != null)
1486 enclosingCandidate.checkPackageAccess(
1487 ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
Joel Borggrén-Francka0051742013-04-19 14:40:31 +01001488 return enclosingCandidate;
J. Duke319a3b92007-12-01 00:00:00 +00001489 }
1490
1491 /**
1492 * Returns the simple name of the underlying class as given in the
1493 * source code. Returns an empty string if the underlying class is
1494 * anonymous.
1495 *
1496 * <p>The simple name of an array is the simple name of the
1497 * component type with "[]" appended. In particular the simple
1498 * name of an array whose component type is anonymous is "[]".
1499 *
1500 * @return the simple name of the underlying class
1501 * @since 1.5
1502 */
1503 public String getSimpleName() {
1504 if (isArray())
1505 return getComponentType().getSimpleName()+"[]";
1506
1507 String simpleName = getSimpleBinaryName();
1508 if (simpleName == null) { // top level class
1509 simpleName = getName();
Otavio Goncalves de Santana8f0e6e32014-05-30 15:46:12 -04001510 return simpleName.substring(simpleName.lastIndexOf('.')+1); // strip the package name
J. Duke319a3b92007-12-01 00:00:00 +00001511 }
Vladimir Ivanov40973932015-04-14 18:03:12 +03001512 return simpleName;
J. Duke319a3b92007-12-01 00:00:00 +00001513 }
1514
1515 /**
Joe Darcy2c7f3d22013-04-08 17:06:20 -07001516 * Return an informative string for the name of this type.
1517 *
1518 * @return an informative string for the name of this type
1519 * @since 1.8
1520 */
1521 public String getTypeName() {
1522 if (isArray()) {
1523 try {
1524 Class<?> cl = this;
1525 int dimensions = 0;
1526 while (cl.isArray()) {
1527 dimensions++;
1528 cl = cl.getComponentType();
1529 }
1530 StringBuilder sb = new StringBuilder();
1531 sb.append(cl.getName());
1532 for (int i = 0; i < dimensions; i++) {
1533 sb.append("[]");
1534 }
1535 return sb.toString();
1536 } catch (Throwable e) { /*FALLTHRU*/ }
1537 }
1538 return getName();
1539 }
1540
1541 /**
J. Duke319a3b92007-12-01 00:00:00 +00001542 * Character.isDigit answers {@code true} to some non-ascii
1543 * digits. This one does not.
1544 */
1545 private static boolean isAsciiDigit(char c) {
1546 return '0' <= c && c <= '9';
1547 }
1548
1549 /**
1550 * Returns the canonical name of the underlying class as
1551 * defined by the Java Language Specification. Returns null if
1552 * the underlying class does not have a canonical name (i.e., if
1553 * it is a local or anonymous class or an array whose component
1554 * type does not have a canonical name).
1555 * @return the canonical name of the underlying class if it exists, and
1556 * {@code null} otherwise.
1557 * @since 1.5
1558 */
1559 public String getCanonicalName() {
1560 if (isArray()) {
1561 String canonicalName = getComponentType().getCanonicalName();
1562 if (canonicalName != null)
1563 return canonicalName + "[]";
1564 else
1565 return null;
1566 }
1567 if (isLocalOrAnonymousClass())
1568 return null;
1569 Class<?> enclosingClass = getEnclosingClass();
1570 if (enclosingClass == null) { // top level class
1571 return getName();
1572 } else {
1573 String enclosingName = enclosingClass.getCanonicalName();
1574 if (enclosingName == null)
1575 return null;
1576 return enclosingName + "." + getSimpleName();
1577 }
1578 }
1579
1580 /**
1581 * Returns {@code true} if and only if the underlying class
1582 * is an anonymous class.
1583 *
1584 * @return {@code true} if and only if this class is an anonymous class.
1585 * @since 1.5
1586 */
1587 public boolean isAnonymousClass() {
1588 return "".equals(getSimpleName());
1589 }
1590
1591 /**
1592 * Returns {@code true} if and only if the underlying class
1593 * is a local class.
1594 *
1595 * @return {@code true} if and only if this class is a local class.
1596 * @since 1.5
1597 */
1598 public boolean isLocalClass() {
1599 return isLocalOrAnonymousClass() && !isAnonymousClass();
1600 }
1601
1602 /**
1603 * Returns {@code true} if and only if the underlying class
1604 * is a member class.
1605 *
1606 * @return {@code true} if and only if this class is a member class.
1607 * @since 1.5
1608 */
1609 public boolean isMemberClass() {
1610 return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
1611 }
1612
1613 /**
1614 * Returns the "simple binary name" of the underlying class, i.e.,
1615 * the binary name without the leading enclosing class name.
1616 * Returns {@code null} if the underlying class is a top level
1617 * class.
1618 */
1619 private String getSimpleBinaryName() {
1620 Class<?> enclosingClass = getEnclosingClass();
1621 if (enclosingClass == null) // top level class
1622 return null;
Vladimir Ivanov40973932015-04-14 18:03:12 +03001623 String name = getSimpleBinaryName0();
1624 if (name == null) // anonymous class
1625 return "";
1626 return name;
J. Duke319a3b92007-12-01 00:00:00 +00001627 }
1628
Vladimir Ivanov40973932015-04-14 18:03:12 +03001629 private native String getSimpleBinaryName0();
1630
J. Duke319a3b92007-12-01 00:00:00 +00001631 /**
1632 * Returns {@code true} if this is a local class or an anonymous
1633 * class. Returns {@code false} otherwise.
1634 */
1635 private boolean isLocalOrAnonymousClass() {
Vladimir Ivanov40973932015-04-14 18:03:12 +03001636 // JVM Spec 4.7.7: A class must have an EnclosingMethod
J. Duke319a3b92007-12-01 00:00:00 +00001637 // attribute if and only if it is a local class or an
1638 // anonymous class.
1639 return getEnclosingMethodInfo() != null;
1640 }
1641
1642 /**
1643 * Returns an array containing {@code Class} objects representing all
1644 * the public classes and interfaces that are members of the class
1645 * represented by this {@code Class} object. This includes public
1646 * class and interface members inherited from superclasses and public class
1647 * and interface members declared by the class. This method returns an
1648 * array of length 0 if this {@code Class} object has no public member
1649 * classes or interfaces. This method also returns an array of length 0 if
1650 * this {@code Class} object represents a primitive type, an array
1651 * class, or void.
1652 *
1653 * @return the array of {@code Class} objects representing the public
Mandy Chung5a360a72013-07-02 15:58:09 -07001654 * members of this class
1655 * @throws SecurityException
1656 * If a security manager, <i>s</i>, is present and
1657 * the caller's class loader is not the same as or an
1658 * ancestor of the class loader for the current class and
1659 * invocation of {@link SecurityManager#checkPackageAccess
1660 * s.checkPackageAccess()} denies access to the package
1661 * of this class.
J. Duke319a3b92007-12-01 00:00:00 +00001662 *
Henry Jenea9a7a82014-06-10 16:18:54 -07001663 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00001664 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07001665 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00001666 public Class<?>[] getClasses() {
Mandy Chung176ed8d2013-04-16 21:39:52 -07001667 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
J. Duke319a3b92007-12-01 00:00:00 +00001668
1669 // Privileged so this implementation can look at DECLARED classes,
1670 // something the caller might not have privilege to do. The code here
1671 // is allowed to look at DECLARED classes because (1) it does not hand
1672 // out anything other than public members and (2) public member access
1673 // has already been ok'd by the SecurityManager.
1674
Martin Buchholz43410942008-03-10 15:07:09 -07001675 return java.security.AccessController.doPrivileged(
Joe Darcyd1122152015-04-23 09:32:35 -07001676 new java.security.PrivilegedAction<>() {
Omair Majidd312aad2011-12-08 13:48:54 -05001677 public Class<?>[] run() {
Stuart Marks6e7cb442010-12-20 13:47:04 -08001678 List<Class<?>> list = new ArrayList<>();
Joe Darcybd9e7da2009-10-06 13:31:41 -07001679 Class<?> currentClass = Class.this;
J. Duke319a3b92007-12-01 00:00:00 +00001680 while (currentClass != null) {
Paul Sandoz51efd872014-01-27 14:29:37 +01001681 for (Class<?> m : currentClass.getDeclaredClasses()) {
1682 if (Modifier.isPublic(m.getModifiers())) {
1683 list.add(m);
J. Duke319a3b92007-12-01 00:00:00 +00001684 }
1685 }
1686 currentClass = currentClass.getSuperclass();
1687 }
Omair Majidd312aad2011-12-08 13:48:54 -05001688 return list.toArray(new Class<?>[0]);
J. Duke319a3b92007-12-01 00:00:00 +00001689 }
1690 });
J. Duke319a3b92007-12-01 00:00:00 +00001691 }
1692
1693
1694 /**
1695 * Returns an array containing {@code Field} objects reflecting all
1696 * the accessible public fields of the class or interface represented by
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001697 * this {@code Class} object.
J. Duke319a3b92007-12-01 00:00:00 +00001698 *
Martin Buchholz08eb67b2014-10-30 07:31:41 -07001699 * <p> If this {@code Class} object represents a class or interface with
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001700 * no accessible public fields, then this method returns an array of length
1701 * 0.
J. Duke319a3b92007-12-01 00:00:00 +00001702 *
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001703 * <p> If this {@code Class} object represents a class, then this method
Martin Buchholz5e65c0f2014-11-06 13:29:36 -08001704 * returns the public fields of the class and of all its superclasses and
1705 * superinterfaces.
J. Duke319a3b92007-12-01 00:00:00 +00001706 *
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001707 * <p> If this {@code Class} object represents an interface, then this
1708 * method returns the fields of the interface and of all its
1709 * superinterfaces.
1710 *
1711 * <p> If this {@code Class} object represents an array type, a primitive
1712 * type, or void, then this method returns an array of length 0.
1713 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001714 * <p> The elements in the returned array are not sorted and are not in any
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001715 * particular order.
J. Duke319a3b92007-12-01 00:00:00 +00001716 *
1717 * @return the array of {@code Field} objects representing the
Mandy Chung5a360a72013-07-02 15:58:09 -07001718 * public fields
1719 * @throws SecurityException
1720 * If a security manager, <i>s</i>, is present and
1721 * the caller's class loader is not the same as or an
1722 * ancestor of the class loader for the current class and
1723 * invocation of {@link SecurityManager#checkPackageAccess
1724 * s.checkPackageAccess()} denies access to the package
1725 * of this class.
J. Duke319a3b92007-12-01 00:00:00 +00001726 *
Henry Jenea9a7a82014-06-10 16:18:54 -07001727 * @since 1.1
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001728 * @jls 8.2 Class Members
1729 * @jls 8.3 Field Declarations
J. Duke319a3b92007-12-01 00:00:00 +00001730 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07001731 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00001732 public Field[] getFields() throws SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07001733 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00001734 return copyFields(privateGetPublicFields(null));
1735 }
1736
1737
1738 /**
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001739 * Returns an array containing {@code Method} objects reflecting all the
1740 * public methods of the class or interface represented by this {@code
1741 * Class} object, including those declared by the class or interface and
1742 * those inherited from superclasses and superinterfaces.
J. Duke319a3b92007-12-01 00:00:00 +00001743 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001744 * <p> If this {@code Class} object represents a type that has multiple
1745 * public methods with the same name and parameter types, but different
1746 * return types, then the returned array has a {@code Method} object for
1747 * each such method.
J. Duke319a3b92007-12-01 00:00:00 +00001748 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001749 * <p> If this {@code Class} object represents a type with a class
1750 * initialization method {@code <clinit>}, then the returned array does
1751 * <em>not</em> have a corresponding {@code Method} object.
1752 *
1753 * <p> If this {@code Class} object represents an array type, then the
1754 * returned array has a {@code Method} object for each of the public
1755 * methods inherited by the array type from {@code Object}. It does not
1756 * contain a {@code Method} object for {@code clone()}.
1757 *
Joel Borggrén-Franck6c535702013-12-04 11:04:05 +01001758 * <p> If this {@code Class} object represents an interface then the
1759 * returned array does not contain any implicitly declared methods from
1760 * {@code Object}. Therefore, if no methods are explicitly declared in
1761 * this interface or any of its superinterfaces then the returned array
1762 * has length 0. (Note that a {@code Class} object which represents a class
1763 * always has public methods, inherited from {@code Object}.)
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001764 *
1765 * <p> If this {@code Class} object represents a primitive type or void,
1766 * then the returned array has length 0.
1767 *
Joel Borggrén-Franck415ea442013-10-22 10:34:12 +02001768 * <p> Static methods declared in superinterfaces of the class or interface
1769 * represented by this {@code Class} object are not considered members of
1770 * the class or interface.
1771 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001772 * <p> The elements in the returned array are not sorted and are not in any
1773 * particular order.
J. Duke319a3b92007-12-01 00:00:00 +00001774 *
1775 * @return the array of {@code Method} objects representing the
Mandy Chung5a360a72013-07-02 15:58:09 -07001776 * public methods of this class
1777 * @throws SecurityException
1778 * If a security manager, <i>s</i>, is present and
1779 * the caller's class loader is not the same as or an
1780 * ancestor of the class loader for the current class and
1781 * invocation of {@link SecurityManager#checkPackageAccess
1782 * s.checkPackageAccess()} denies access to the package
1783 * of this class.
J. Duke319a3b92007-12-01 00:00:00 +00001784 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001785 * @jls 8.2 Class Members
1786 * @jls 8.4 Method Declarations
Henry Jenea9a7a82014-06-10 16:18:54 -07001787 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00001788 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07001789 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00001790 public Method[] getMethods() throws SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07001791 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00001792 return copyMethods(privateGetPublicMethods());
1793 }
1794
1795
1796 /**
1797 * Returns an array containing {@code Constructor} objects reflecting
1798 * all the public constructors of the class represented by this
1799 * {@code Class} object. An array of length 0 is returned if the
1800 * class has no public constructors, or if the class is an array class, or
1801 * if the class reflects a primitive type or void.
1802 *
1803 * Note that while this method returns an array of {@code
1804 * Constructor<T>} objects (that is an array of constructors from
1805 * this class), the return type of this method is {@code
1806 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1807 * might be expected. This less informative return type is
1808 * necessary since after being returned from this method, the
1809 * array could be modified to hold {@code Constructor} objects for
1810 * different classes, which would violate the type guarantees of
1811 * {@code Constructor<T>[]}.
1812 *
1813 * @return the array of {@code Constructor} objects representing the
Mandy Chung5a360a72013-07-02 15:58:09 -07001814 * public constructors of this class
1815 * @throws SecurityException
1816 * If a security manager, <i>s</i>, is present and
1817 * the caller's class loader is not the same as or an
1818 * ancestor of the class loader for the current class and
1819 * invocation of {@link SecurityManager#checkPackageAccess
1820 * s.checkPackageAccess()} denies access to the package
1821 * of this class.
J. Duke319a3b92007-12-01 00:00:00 +00001822 *
Henry Jenea9a7a82014-06-10 16:18:54 -07001823 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00001824 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07001825 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00001826 public Constructor<?>[] getConstructors() throws SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07001827 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00001828 return copyConstructors(privateGetDeclaredConstructors(true));
1829 }
1830
1831
1832 /**
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001833 * Returns a {@code Field} object that reflects the specified public member
1834 * field of the class or interface represented by this {@code Class}
1835 * object. The {@code name} parameter is a {@code String} specifying the
1836 * simple name of the desired field.
J. Duke319a3b92007-12-01 00:00:00 +00001837 *
1838 * <p> The field to be reflected is determined by the algorithm that
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001839 * follows. Let C be the class or interface represented by this object:
1840 *
J. Duke319a3b92007-12-01 00:00:00 +00001841 * <OL>
1842 * <LI> If C declares a public field with the name specified, that is the
1843 * field to be reflected.</LI>
1844 * <LI> If no field was found in step 1 above, this algorithm is applied
1845 * recursively to each direct superinterface of C. The direct
1846 * superinterfaces are searched in the order they were declared.</LI>
1847 * <LI> If no field was found in steps 1 and 2 above, and C has a
1848 * superclass S, then this algorithm is invoked recursively upon S.
1849 * If C has no superclass, then a {@code NoSuchFieldException}
1850 * is thrown.</LI>
1851 * </OL>
1852 *
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001853 * <p> If this {@code Class} object represents an array type, then this
1854 * method does not find the {@code length} field of the array type.
J. Duke319a3b92007-12-01 00:00:00 +00001855 *
1856 * @param name the field name
Mandy Chung5a360a72013-07-02 15:58:09 -07001857 * @return the {@code Field} object of this class specified by
1858 * {@code name}
1859 * @throws NoSuchFieldException if a field with the specified name is
1860 * not found.
1861 * @throws NullPointerException if {@code name} is {@code null}
1862 * @throws SecurityException
1863 * If a security manager, <i>s</i>, is present and
1864 * the caller's class loader is not the same as or an
1865 * ancestor of the class loader for the current class and
1866 * invocation of {@link SecurityManager#checkPackageAccess
1867 * s.checkPackageAccess()} denies access to the package
1868 * of this class.
J. Duke319a3b92007-12-01 00:00:00 +00001869 *
Henry Jenea9a7a82014-06-10 16:18:54 -07001870 * @since 1.1
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02001871 * @jls 8.2 Class Members
1872 * @jls 8.3 Field Declarations
J. Duke319a3b92007-12-01 00:00:00 +00001873 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07001874 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00001875 public Field getField(String name)
1876 throws NoSuchFieldException, SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07001877 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00001878 Field field = getField0(name);
1879 if (field == null) {
1880 throw new NoSuchFieldException(name);
1881 }
1882 return field;
1883 }
1884
1885
1886 /**
1887 * Returns a {@code Method} object that reflects the specified public
1888 * member method of the class or interface represented by this
1889 * {@code Class} object. The {@code name} parameter is a
1890 * {@code String} specifying the simple name of the desired method. The
1891 * {@code parameterTypes} parameter is an array of {@code Class}
1892 * objects that identify the method's formal parameter types, in declared
1893 * order. If {@code parameterTypes} is {@code null}, it is
1894 * treated as if it were an empty array.
1895 *
Joel Borggrén-Franck6c535702013-12-04 11:04:05 +01001896 * <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a
J. Duke319a3b92007-12-01 00:00:00 +00001897 * {@code NoSuchMethodException} is raised. Otherwise, the method to
1898 * be reflected is determined by the algorithm that follows. Let C be the
Joel Borggrén-Franck6c535702013-12-04 11:04:05 +01001899 * class or interface represented by this object:
J. Duke319a3b92007-12-01 00:00:00 +00001900 * <OL>
Joel Borggrén-Franck6c535702013-12-04 11:04:05 +01001901 * <LI> C is searched for a <I>matching method</I>, as defined below. If a
1902 * matching method is found, it is reflected.</LI>
1903 * <LI> If no matching method is found by step 1 then:
1904 * <OL TYPE="a">
1905 * <LI> If C is a class other than {@code Object}, then this algorithm is
1906 * invoked recursively on the superclass of C.</LI>
1907 * <LI> If C is the class {@code Object}, or if C is an interface, then
1908 * the superinterfaces of C (if any) are searched for a matching
1909 * method. If any such method is found, it is reflected.</LI>
1910 * </OL></LI>
J. Duke319a3b92007-12-01 00:00:00 +00001911 * </OL>
1912 *
Joel Borggrén-Franck6c535702013-12-04 11:04:05 +01001913 * <p> To find a matching method in a class or interface C:&nbsp; If C
1914 * declares exactly one public method with the specified name and exactly
1915 * the same formal parameter types, that is the method reflected. If more
1916 * than one such method is found in C, and one of these methods has a
1917 * return type that is more specific than any of the others, that method is
1918 * reflected; otherwise one of the methods is chosen arbitrarily.
J. Duke319a3b92007-12-01 00:00:00 +00001919 *
1920 * <p>Note that there may be more than one matching method in a
1921 * class because while the Java language forbids a class to
1922 * declare multiple methods with the same signature but different
1923 * return types, the Java virtual machine does not. This
1924 * increased flexibility in the virtual machine can be used to
1925 * implement various language features. For example, covariant
1926 * returns can be implemented with {@linkplain
1927 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1928 * method and the method being overridden would have the same
1929 * signature but different return types.
1930 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001931 * <p> If this {@code Class} object represents an array type, then this
1932 * method does not find the {@code clone()} method.
J. Duke319a3b92007-12-01 00:00:00 +00001933 *
Joel Borggrén-Franck415ea442013-10-22 10:34:12 +02001934 * <p> Static methods declared in superinterfaces of the class or interface
1935 * represented by this {@code Class} object are not considered members of
1936 * the class or interface.
1937 *
J. Duke319a3b92007-12-01 00:00:00 +00001938 * @param name the name of the method
1939 * @param parameterTypes the list of parameters
1940 * @return the {@code Method} object that matches the specified
Mandy Chung5a360a72013-07-02 15:58:09 -07001941 * {@code name} and {@code parameterTypes}
1942 * @throws NoSuchMethodException if a matching method is not found
1943 * or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
1944 * @throws NullPointerException if {@code name} is {@code null}
1945 * @throws SecurityException
1946 * If a security manager, <i>s</i>, is present and
1947 * the caller's class loader is not the same as or an
1948 * ancestor of the class loader for the current class and
1949 * invocation of {@link SecurityManager#checkPackageAccess
1950 * s.checkPackageAccess()} denies access to the package
1951 * of this class.
J. Duke319a3b92007-12-01 00:00:00 +00001952 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02001953 * @jls 8.2 Class Members
1954 * @jls 8.4 Method Declarations
Henry Jenea9a7a82014-06-10 16:18:54 -07001955 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00001956 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07001957 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00001958 public Method getMethod(String name, Class<?>... parameterTypes)
1959 throws NoSuchMethodException, SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07001960 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
Joel Borggrén-Franck415ea442013-10-22 10:34:12 +02001961 Method method = getMethod0(name, parameterTypes, true);
J. Duke319a3b92007-12-01 00:00:00 +00001962 if (method == null) {
1963 throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
1964 }
1965 return method;
1966 }
1967
1968
1969 /**
1970 * Returns a {@code Constructor} object that reflects the specified
1971 * public constructor of the class represented by this {@code Class}
1972 * object. The {@code parameterTypes} parameter is an array of
1973 * {@code Class} objects that identify the constructor's formal
1974 * parameter types, in declared order.
1975 *
1976 * If this {@code Class} object represents an inner class
1977 * declared in a non-static context, the formal parameter types
1978 * include the explicit enclosing instance as the first parameter.
1979 *
1980 * <p> The constructor to reflect is the public constructor of the class
1981 * represented by this {@code Class} object whose formal parameter
1982 * types match those specified by {@code parameterTypes}.
1983 *
1984 * @param parameterTypes the parameter array
1985 * @return the {@code Constructor} object of the public constructor that
Mandy Chung5a360a72013-07-02 15:58:09 -07001986 * matches the specified {@code parameterTypes}
1987 * @throws NoSuchMethodException if a matching method is not found.
1988 * @throws SecurityException
1989 * If a security manager, <i>s</i>, is present and
1990 * the caller's class loader is not the same as or an
1991 * ancestor of the class loader for the current class and
1992 * invocation of {@link SecurityManager#checkPackageAccess
1993 * s.checkPackageAccess()} denies access to the package
1994 * of this class.
J. Duke319a3b92007-12-01 00:00:00 +00001995 *
Henry Jenea9a7a82014-06-10 16:18:54 -07001996 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00001997 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07001998 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00001999 public Constructor<T> getConstructor(Class<?>... parameterTypes)
2000 throws NoSuchMethodException, SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07002001 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00002002 return getConstructor0(parameterTypes, Member.PUBLIC);
2003 }
2004
2005
2006 /**
2007 * Returns an array of {@code Class} objects reflecting all the
2008 * classes and interfaces declared as members of the class represented by
2009 * this {@code Class} object. This includes public, protected, default
2010 * (package) access, and private classes and interfaces declared by the
2011 * class, but excludes inherited classes and interfaces. This method
2012 * returns an array of length 0 if the class declares no classes or
2013 * interfaces as members, or if this {@code Class} object represents a
2014 * primitive type, an array class, or void.
2015 *
2016 * @return the array of {@code Class} objects representing all the
Mandy Chung5a360a72013-07-02 15:58:09 -07002017 * declared members of this class
2018 * @throws SecurityException
2019 * If a security manager, <i>s</i>, is present and any of the
2020 * following conditions is met:
J. Duke319a3b92007-12-01 00:00:00 +00002021 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002022 * <ul>
J. Duke319a3b92007-12-01 00:00:00 +00002023 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002024 * <li> the caller's class loader is not the same as the
2025 * class loader of this class and invocation of
2026 * {@link SecurityManager#checkPermission
2027 * s.checkPermission} method with
2028 * {@code RuntimePermission("accessDeclaredMembers")}
2029 * denies access to the declared classes within this class
J. Duke319a3b92007-12-01 00:00:00 +00002030 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002031 * <li> the caller's class loader is not the same as or an
2032 * ancestor of the class loader for the current class and
2033 * invocation of {@link SecurityManager#checkPackageAccess
2034 * s.checkPackageAccess()} denies access to the package
2035 * of this class
J. Duke319a3b92007-12-01 00:00:00 +00002036 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002037 * </ul>
J. Duke319a3b92007-12-01 00:00:00 +00002038 *
Henry Jenea9a7a82014-06-10 16:18:54 -07002039 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00002040 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07002041 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00002042 public Class<?>[] getDeclaredClasses() throws SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07002043 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
J. Duke319a3b92007-12-01 00:00:00 +00002044 return getDeclaredClasses0();
2045 }
2046
2047
2048 /**
2049 * Returns an array of {@code Field} objects reflecting all the fields
2050 * declared by the class or interface represented by this
2051 * {@code Class} object. This includes public, protected, default
2052 * (package) access, and private fields, but excludes inherited fields.
J. Duke319a3b92007-12-01 00:00:00 +00002053 *
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02002054 * <p> If this {@code Class} object represents a class or interface with no
2055 * declared fields, then this method returns an array of length 0.
2056 *
2057 * <p> If this {@code Class} object represents an array type, a primitive
2058 * type, or void, then this method returns an array of length 0.
2059 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02002060 * <p> The elements in the returned array are not sorted and are not in any
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02002061 * particular order.
J. Duke319a3b92007-12-01 00:00:00 +00002062 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002063 * @return the array of {@code Field} objects representing all the
2064 * declared fields of this class
2065 * @throws SecurityException
2066 * If a security manager, <i>s</i>, is present and any of the
2067 * following conditions is met:
J. Duke319a3b92007-12-01 00:00:00 +00002068 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002069 * <ul>
J. Duke319a3b92007-12-01 00:00:00 +00002070 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002071 * <li> the caller's class loader is not the same as the
2072 * class loader of this class and invocation of
2073 * {@link SecurityManager#checkPermission
2074 * s.checkPermission} method with
2075 * {@code RuntimePermission("accessDeclaredMembers")}
2076 * denies access to the declared fields within this class
J. Duke319a3b92007-12-01 00:00:00 +00002077 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002078 * <li> the caller's class loader is not the same as or an
2079 * ancestor of the class loader for the current class and
2080 * invocation of {@link SecurityManager#checkPackageAccess
2081 * s.checkPackageAccess()} denies access to the package
2082 * of this class
J. Duke319a3b92007-12-01 00:00:00 +00002083 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002084 * </ul>
J. Duke319a3b92007-12-01 00:00:00 +00002085 *
Henry Jenea9a7a82014-06-10 16:18:54 -07002086 * @since 1.1
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02002087 * @jls 8.2 Class Members
2088 * @jls 8.3 Field Declarations
J. Duke319a3b92007-12-01 00:00:00 +00002089 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07002090 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00002091 public Field[] getDeclaredFields() throws SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07002092 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00002093 return copyFields(privateGetDeclaredFields(false));
2094 }
2095
2096
2097 /**
J. Duke319a3b92007-12-01 00:00:00 +00002098 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02002099 * Returns an array containing {@code Method} objects reflecting all the
2100 * declared methods of the class or interface represented by this {@code
2101 * Class} object, including public, protected, default (package)
2102 * access, and private methods, but excluding inherited methods.
2103 *
2104 * <p> If this {@code Class} object represents a type that has multiple
2105 * declared methods with the same name and parameter types, but different
2106 * return types, then the returned array has a {@code Method} object for
2107 * each such method.
2108 *
2109 * <p> If this {@code Class} object represents a type that has a class
2110 * initialization method {@code <clinit>}, then the returned array does
2111 * <em>not</em> have a corresponding {@code Method} object.
2112 *
2113 * <p> If this {@code Class} object represents a class or interface with no
2114 * declared methods, then the returned array has length 0.
2115 *
2116 * <p> If this {@code Class} object represents an array type, a primitive
2117 * type, or void, then the returned array has length 0.
2118 *
2119 * <p> The elements in the returned array are not sorted and are not in any
2120 * particular order.
J. Duke319a3b92007-12-01 00:00:00 +00002121 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002122 * @return the array of {@code Method} objects representing all the
2123 * declared methods of this class
2124 * @throws SecurityException
2125 * If a security manager, <i>s</i>, is present and any of the
2126 * following conditions is met:
J. Duke319a3b92007-12-01 00:00:00 +00002127 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002128 * <ul>
J. Duke319a3b92007-12-01 00:00:00 +00002129 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002130 * <li> the caller's class loader is not the same as the
2131 * class loader of this class and invocation of
2132 * {@link SecurityManager#checkPermission
2133 * s.checkPermission} method with
2134 * {@code RuntimePermission("accessDeclaredMembers")}
2135 * denies access to the declared methods within this class
J. Duke319a3b92007-12-01 00:00:00 +00002136 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002137 * <li> the caller's class loader is not the same as or an
2138 * ancestor of the class loader for the current class and
2139 * invocation of {@link SecurityManager#checkPackageAccess
2140 * s.checkPackageAccess()} denies access to the package
2141 * of this class
J. Duke319a3b92007-12-01 00:00:00 +00002142 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002143 * </ul>
J. Duke319a3b92007-12-01 00:00:00 +00002144 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02002145 * @jls 8.2 Class Members
2146 * @jls 8.4 Method Declarations
Henry Jenea9a7a82014-06-10 16:18:54 -07002147 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00002148 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07002149 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00002150 public Method[] getDeclaredMethods() throws SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07002151 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00002152 return copyMethods(privateGetDeclaredMethods(false));
2153 }
2154
2155
2156 /**
2157 * Returns an array of {@code Constructor} objects reflecting all the
2158 * constructors declared by the class represented by this
2159 * {@code Class} object. These are public, protected, default
2160 * (package) access, and private constructors. The elements in the array
2161 * returned are not sorted and are not in any particular order. If the
2162 * class has a default constructor, it is included in the returned array.
2163 * This method returns an array of length 0 if this {@code Class}
2164 * object represents an interface, a primitive type, an array class, or
2165 * void.
2166 *
2167 * <p> See <em>The Java Language Specification</em>, section 8.2.
2168 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002169 * @return the array of {@code Constructor} objects representing all the
2170 * declared constructors of this class
2171 * @throws SecurityException
2172 * If a security manager, <i>s</i>, is present and any of the
2173 * following conditions is met:
J. Duke319a3b92007-12-01 00:00:00 +00002174 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002175 * <ul>
J. Duke319a3b92007-12-01 00:00:00 +00002176 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002177 * <li> the caller's class loader is not the same as the
2178 * class loader of this class and invocation of
2179 * {@link SecurityManager#checkPermission
2180 * s.checkPermission} method with
2181 * {@code RuntimePermission("accessDeclaredMembers")}
2182 * denies access to the declared constructors within this class
J. Duke319a3b92007-12-01 00:00:00 +00002183 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002184 * <li> the caller's class loader is not the same as or an
2185 * ancestor of the class loader for the current class and
2186 * invocation of {@link SecurityManager#checkPackageAccess
2187 * s.checkPackageAccess()} denies access to the package
2188 * of this class
J. Duke319a3b92007-12-01 00:00:00 +00002189 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002190 * </ul>
J. Duke319a3b92007-12-01 00:00:00 +00002191 *
Henry Jenea9a7a82014-06-10 16:18:54 -07002192 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00002193 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07002194 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00002195 public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07002196 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00002197 return copyConstructors(privateGetDeclaredConstructors(false));
2198 }
2199
2200
2201 /**
2202 * Returns a {@code Field} object that reflects the specified declared
2203 * field of the class or interface represented by this {@code Class}
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02002204 * object. The {@code name} parameter is a {@code String} that specifies
2205 * the simple name of the desired field.
2206 *
2207 * <p> If this {@code Class} object represents an array type, then this
2208 * method does not find the {@code length} field of the array type.
J. Duke319a3b92007-12-01 00:00:00 +00002209 *
2210 * @param name the name of the field
Mandy Chung5a360a72013-07-02 15:58:09 -07002211 * @return the {@code Field} object for the specified field in this
2212 * class
2213 * @throws NoSuchFieldException if a field with the specified name is
2214 * not found.
2215 * @throws NullPointerException if {@code name} is {@code null}
2216 * @throws SecurityException
2217 * If a security manager, <i>s</i>, is present and any of the
2218 * following conditions is met:
J. Duke319a3b92007-12-01 00:00:00 +00002219 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002220 * <ul>
J. Duke319a3b92007-12-01 00:00:00 +00002221 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002222 * <li> the caller's class loader is not the same as the
2223 * class loader of this class and invocation of
2224 * {@link SecurityManager#checkPermission
2225 * s.checkPermission} method with
2226 * {@code RuntimePermission("accessDeclaredMembers")}
2227 * denies access to the declared field
J. Duke319a3b92007-12-01 00:00:00 +00002228 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002229 * <li> the caller's class loader is not the same as or an
2230 * ancestor of the class loader for the current class and
2231 * invocation of {@link SecurityManager#checkPackageAccess
2232 * s.checkPackageAccess()} denies access to the package
2233 * of this class
J. Duke319a3b92007-12-01 00:00:00 +00002234 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002235 * </ul>
J. Duke319a3b92007-12-01 00:00:00 +00002236 *
Henry Jenea9a7a82014-06-10 16:18:54 -07002237 * @since 1.1
Joel Borggrén-Franck80075902013-09-06 14:20:12 +02002238 * @jls 8.2 Class Members
2239 * @jls 8.3 Field Declarations
J. Duke319a3b92007-12-01 00:00:00 +00002240 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07002241 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00002242 public Field getDeclaredField(String name)
2243 throws NoSuchFieldException, SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07002244 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00002245 Field field = searchFields(privateGetDeclaredFields(false), name);
2246 if (field == null) {
2247 throw new NoSuchFieldException(name);
2248 }
2249 return field;
2250 }
2251
2252
2253 /**
2254 * Returns a {@code Method} object that reflects the specified
2255 * declared method of the class or interface represented by this
2256 * {@code Class} object. The {@code name} parameter is a
2257 * {@code String} that specifies the simple name of the desired
2258 * method, and the {@code parameterTypes} parameter is an array of
2259 * {@code Class} objects that identify the method's formal parameter
2260 * types, in declared order. If more than one method with the same
2261 * parameter types is declared in a class, and one of these methods has a
2262 * return type that is more specific than any of the others, that method is
2263 * returned; otherwise one of the methods is chosen arbitrarily. If the
2264 * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2265 * is raised.
2266 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02002267 * <p> If this {@code Class} object represents an array type, then this
2268 * method does not find the {@code clone()} method.
2269 *
J. Duke319a3b92007-12-01 00:00:00 +00002270 * @param name the name of the method
2271 * @param parameterTypes the parameter array
Mandy Chung5a360a72013-07-02 15:58:09 -07002272 * @return the {@code Method} object for the method of this class
2273 * matching the specified name and parameters
2274 * @throws NoSuchMethodException if a matching method is not found.
2275 * @throws NullPointerException if {@code name} is {@code null}
2276 * @throws SecurityException
2277 * If a security manager, <i>s</i>, is present and any of the
2278 * following conditions is met:
J. Duke319a3b92007-12-01 00:00:00 +00002279 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002280 * <ul>
J. Duke319a3b92007-12-01 00:00:00 +00002281 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002282 * <li> the caller's class loader is not the same as the
2283 * class loader of this class and invocation of
2284 * {@link SecurityManager#checkPermission
2285 * s.checkPermission} method with
2286 * {@code RuntimePermission("accessDeclaredMembers")}
2287 * denies access to the declared method
J. Duke319a3b92007-12-01 00:00:00 +00002288 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002289 * <li> the caller's class loader is not the same as or an
2290 * ancestor of the class loader for the current class and
2291 * invocation of {@link SecurityManager#checkPackageAccess
2292 * s.checkPackageAccess()} denies access to the package
2293 * of this class
J. Duke319a3b92007-12-01 00:00:00 +00002294 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002295 * </ul>
J. Duke319a3b92007-12-01 00:00:00 +00002296 *
Joel Borggrén-Franck9a30d422013-09-11 09:45:52 +02002297 * @jls 8.2 Class Members
2298 * @jls 8.4 Method Declarations
Henry Jenea9a7a82014-06-10 16:18:54 -07002299 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00002300 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07002301 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00002302 public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2303 throws NoSuchMethodException, SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07002304 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00002305 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2306 if (method == null) {
2307 throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
2308 }
2309 return method;
2310 }
2311
2312
2313 /**
2314 * Returns a {@code Constructor} object that reflects the specified
2315 * constructor of the class or interface represented by this
2316 * {@code Class} object. The {@code parameterTypes} parameter is
2317 * an array of {@code Class} objects that identify the constructor's
2318 * formal parameter types, in declared order.
2319 *
2320 * If this {@code Class} object represents an inner class
2321 * declared in a non-static context, the formal parameter types
2322 * include the explicit enclosing instance as the first parameter.
2323 *
2324 * @param parameterTypes the parameter array
Mandy Chung5a360a72013-07-02 15:58:09 -07002325 * @return The {@code Constructor} object for the constructor with the
2326 * specified parameter list
2327 * @throws NoSuchMethodException if a matching method is not found.
2328 * @throws SecurityException
2329 * If a security manager, <i>s</i>, is present and any of the
2330 * following conditions is met:
J. Duke319a3b92007-12-01 00:00:00 +00002331 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002332 * <ul>
J. Duke319a3b92007-12-01 00:00:00 +00002333 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002334 * <li> the caller's class loader is not the same as the
2335 * class loader of this class and invocation of
2336 * {@link SecurityManager#checkPermission
2337 * s.checkPermission} method with
2338 * {@code RuntimePermission("accessDeclaredMembers")}
2339 * denies access to the declared constructor
J. Duke319a3b92007-12-01 00:00:00 +00002340 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002341 * <li> the caller's class loader is not the same as or an
2342 * ancestor of the class loader for the current class and
2343 * invocation of {@link SecurityManager#checkPackageAccess
2344 * s.checkPackageAccess()} denies access to the package
2345 * of this class
J. Duke319a3b92007-12-01 00:00:00 +00002346 *
Mandy Chung5a360a72013-07-02 15:58:09 -07002347 * </ul>
J. Duke319a3b92007-12-01 00:00:00 +00002348 *
Henry Jenea9a7a82014-06-10 16:18:54 -07002349 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00002350 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07002351 @CallerSensitive
J. Duke319a3b92007-12-01 00:00:00 +00002352 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2353 throws NoSuchMethodException, SecurityException {
Mandy Chung176ed8d2013-04-16 21:39:52 -07002354 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
J. Duke319a3b92007-12-01 00:00:00 +00002355 return getConstructor0(parameterTypes, Member.DECLARED);
2356 }
2357
2358 /**
Alan Batemandb4d3832016-03-17 19:04:16 +00002359 * Finds a resource with a given name. If this class is in a named {@link
2360 * Module Module}, and the caller of this method is in the same module,
2361 * then this method will attempt to find the resource in that module.
2362 * Otherwise, the rules for searching resources
J. Duke319a3b92007-12-01 00:00:00 +00002363 * associated with a given class are implemented by the defining
2364 * {@linkplain ClassLoader class loader} of the class. This method
2365 * delegates to this object's class loader. If this object was loaded by
2366 * the bootstrap class loader, the method delegates to {@link
2367 * ClassLoader#getSystemResourceAsStream}.
2368 *
Alan Batemandb4d3832016-03-17 19:04:16 +00002369 * <p> Before finding a resource in the caller's module or delegation to a
2370 * class loader, an absolute resource name is constructed from the given
2371 * resource name using this algorithm:
J. Duke319a3b92007-12-01 00:00:00 +00002372 *
2373 * <ul>
2374 *
2375 * <li> If the {@code name} begins with a {@code '/'}
2376 * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2377 * portion of the {@code name} following the {@code '/'}.
2378 *
2379 * <li> Otherwise, the absolute name is of the following form:
2380 *
2381 * <blockquote>
2382 * {@code modified_package_name/name}
2383 * </blockquote>
2384 *
2385 * <p> Where the {@code modified_package_name} is the package name of this
2386 * object with {@code '/'} substituted for {@code '.'}
2387 * (<tt>'&#92;u002e'</tt>).
2388 *
2389 * </ul>
2390 *
2391 * @param name name of the desired resource
Alan Batemandb4d3832016-03-17 19:04:16 +00002392 * @return A {@link java.io.InputStream} object or {@code null} if
2393 * no resource with this name is found
J. Duke319a3b92007-12-01 00:00:00 +00002394 * @throws NullPointerException If {@code name} is {@code null}
Henry Jenea9a7a82014-06-10 16:18:54 -07002395 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00002396 */
Alan Batemandb4d3832016-03-17 19:04:16 +00002397 @CallerSensitive
2398 public InputStream getResourceAsStream(String name) {
J. Duke319a3b92007-12-01 00:00:00 +00002399 name = resolveName(name);
Alan Batemandb4d3832016-03-17 19:04:16 +00002400
2401 // if this Class and the caller are in the same named module
2402 // then attempt to get an input stream to the resource in the
2403 // module
2404 Module module = getModule();
2405 if (module.isNamed()) {
2406 Class<?> caller = Reflection.getCallerClass();
2407 if (caller != null && caller.getModule() == module) {
2408 ClassLoader cl = getClassLoader0();
2409 String mn = module.getName();
2410 try {
2411
2412 // special-case built-in class loaders to avoid the
2413 // need for a URL connection
2414 if (cl == null) {
2415 return BootLoader.findResourceAsStream(mn, name);
2416 } else if (cl instanceof BuiltinClassLoader) {
2417 return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name);
2418 } else {
2419 URL url = cl.findResource(mn, name);
2420 return (url != null) ? url.openStream() : null;
2421 }
2422
2423 } catch (IOException | SecurityException e) {
2424 return null;
2425 }
2426 }
J. Duke319a3b92007-12-01 00:00:00 +00002427 }
Alan Batemandb4d3832016-03-17 19:04:16 +00002428
2429 // this Class and caller not in the same named module
2430 ClassLoader cl = getClassLoader0();
2431 if (cl == null) {
2432 return ClassLoader.getSystemResourceAsStream(name);
2433 } else {
2434 return cl.getResourceAsStream(name);
2435 }
J. Duke319a3b92007-12-01 00:00:00 +00002436 }
2437
2438 /**
Alan Batemandb4d3832016-03-17 19:04:16 +00002439 * Finds a resource with a given name. If this class is in a named {@link
2440 * Module Module}, and the caller of this method is in the same module,
2441 * then this method will attempt to find the resource in that module.
2442 * Otherwise, the rules for searching resources
J. Duke319a3b92007-12-01 00:00:00 +00002443 * associated with a given class are implemented by the defining
2444 * {@linkplain ClassLoader class loader} of the class. This method
Alan Batemandb4d3832016-03-17 19:04:16 +00002445 * delegates to this object's class loader. If this object was loaded by
J. Duke319a3b92007-12-01 00:00:00 +00002446 * the bootstrap class loader, the method delegates to {@link
2447 * ClassLoader#getSystemResource}.
2448 *
2449 * <p> Before delegation, an absolute resource name is constructed from the
2450 * given resource name using this algorithm:
2451 *
2452 * <ul>
2453 *
2454 * <li> If the {@code name} begins with a {@code '/'}
2455 * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2456 * portion of the {@code name} following the {@code '/'}.
2457 *
2458 * <li> Otherwise, the absolute name is of the following form:
2459 *
2460 * <blockquote>
2461 * {@code modified_package_name/name}
2462 * </blockquote>
2463 *
2464 * <p> Where the {@code modified_package_name} is the package name of this
2465 * object with {@code '/'} substituted for {@code '.'}
2466 * (<tt>'&#92;u002e'</tt>).
2467 *
2468 * </ul>
2469 *
2470 * @param name name of the desired resource
Alan Batemandb4d3832016-03-17 19:04:16 +00002471 * @return A {@link java.net.URL} object; {@code null} if no
2472 * resource with this name is found or the resource cannot
2473 * be located by a URL.
Henry Jenea9a7a82014-06-10 16:18:54 -07002474 * @since 1.1
J. Duke319a3b92007-12-01 00:00:00 +00002475 */
Alan Batemandb4d3832016-03-17 19:04:16 +00002476 @CallerSensitive
2477 public URL getResource(String name) {
J. Duke319a3b92007-12-01 00:00:00 +00002478 name = resolveName(name);
Alan Batemandb4d3832016-03-17 19:04:16 +00002479
2480 // if this Class and the caller are in the same named module
2481 // then attempt to get URL to the resource in the module
2482 Module module = getModule();
2483 if (module.isNamed()) {
2484 Class<?> caller = Reflection.getCallerClass();
2485 if (caller != null && caller.getModule() == module) {
2486 String mn = getModule().getName();
2487 ClassLoader cl = getClassLoader0();
2488 try {
2489 if (cl == null) {
2490 return BootLoader.findResource(mn, name);
2491 } else {
2492 return cl.findResource(mn, name);
2493 }
2494 } catch (IOException ioe) {
2495 return null;
2496 }
2497 }
J. Duke319a3b92007-12-01 00:00:00 +00002498 }
Alan Batemandb4d3832016-03-17 19:04:16 +00002499
2500 ClassLoader cl = getClassLoader0();
2501 if (cl == null) {
2502 return ClassLoader.getSystemResource(name);
2503 } else {
2504 return cl.getResource(name);
2505 }
J. Duke319a3b92007-12-01 00:00:00 +00002506 }
2507
J. Duke319a3b92007-12-01 00:00:00 +00002508 /** protection domain returned when the internal domain is null */
2509 private static java.security.ProtectionDomain allPermDomain;
2510
2511
2512 /**
2513 * Returns the {@code ProtectionDomain} of this class. If there is a
2514 * security manager installed, this method first calls the security
2515 * manager's {@code checkPermission} method with a
2516 * {@code RuntimePermission("getProtectionDomain")} permission to
2517 * ensure it's ok to get the
2518 * {@code ProtectionDomain}.
2519 *
2520 * @return the ProtectionDomain of this class
2521 *
2522 * @throws SecurityException
2523 * if a security manager exists and its
2524 * {@code checkPermission} method doesn't allow
2525 * getting the ProtectionDomain.
2526 *
2527 * @see java.security.ProtectionDomain
2528 * @see SecurityManager#checkPermission
2529 * @see java.lang.RuntimePermission
2530 * @since 1.2
2531 */
2532 public java.security.ProtectionDomain getProtectionDomain() {
2533 SecurityManager sm = System.getSecurityManager();
2534 if (sm != null) {
2535 sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2536 }
2537 java.security.ProtectionDomain pd = getProtectionDomain0();
2538 if (pd == null) {
2539 if (allPermDomain == null) {
2540 java.security.Permissions perms =
2541 new java.security.Permissions();
2542 perms.add(SecurityConstants.ALL_PERMISSION);
2543 allPermDomain =
2544 new java.security.ProtectionDomain(null, perms);
2545 }
2546 pd = allPermDomain;
2547 }
2548 return pd;
2549 }
2550
2551
2552 /**
2553 * Returns the ProtectionDomain of this class.
2554 */
2555 private native java.security.ProtectionDomain getProtectionDomain0();
2556
J. Duke319a3b92007-12-01 00:00:00 +00002557 /*
2558 * Return the Virtual Machine's Class object for the named
2559 * primitive type.
2560 */
Omair Majidd312aad2011-12-08 13:48:54 -05002561 static native Class<?> getPrimitiveClass(String name);
J. Duke319a3b92007-12-01 00:00:00 +00002562
J. Duke319a3b92007-12-01 00:00:00 +00002563 /*
2564 * Check if client is allowed to access members. If access is denied,
2565 * throw a SecurityException.
2566 *
Joel Borggrén-Francka638aed2013-05-07 13:23:08 +02002567 * This method also enforces package access.
2568 *
J. Duke319a3b92007-12-01 00:00:00 +00002569 * <p> Default policy: allow all clients access with normal Java access
2570 * control.
2571 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07002572 private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
2573 final SecurityManager s = System.getSecurityManager();
J. Duke319a3b92007-12-01 00:00:00 +00002574 if (s != null) {
Mandy Chung5a360a72013-07-02 15:58:09 -07002575 /* Default policy allows access to all {@link Member#PUBLIC} members,
2576 * as well as access to classes that have the same class loader as the caller.
2577 * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
2578 * permission.
2579 */
Mandy Chung176ed8d2013-04-16 21:39:52 -07002580 final ClassLoader ccl = ClassLoader.getClassLoader(caller);
2581 final ClassLoader cl = getClassLoader0();
Mandy Chung5a360a72013-07-02 15:58:09 -07002582 if (which != Member.PUBLIC) {
2583 if (ccl != cl) {
2584 s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
Mandy Chung176ed8d2013-04-16 21:39:52 -07002585 }
Mandy Chung176ed8d2013-04-16 21:39:52 -07002586 }
Joel Borggrén-Francka638aed2013-05-07 13:23:08 +02002587 this.checkPackageAccess(ccl, checkProxyInterfaces);
2588 }
2589 }
Mandy Chung176ed8d2013-04-16 21:39:52 -07002590
Joel Borggrén-Francka638aed2013-05-07 13:23:08 +02002591 /*
2592 * Checks if a client loaded in ClassLoader ccl is allowed to access this
2593 * class under the current package access policy. If access is denied,
2594 * throw a SecurityException.
2595 */
2596 private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {
2597 final SecurityManager s = System.getSecurityManager();
2598 if (s != null) {
2599 final ClassLoader cl = getClassLoader0();
Mandy Chung176ed8d2013-04-16 21:39:52 -07002600
Mandy Chungd3ccd202012-11-02 16:50:23 -07002601 if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
J. Duke319a3b92007-12-01 00:00:00 +00002602 String name = this.getName();
2603 int i = name.lastIndexOf('.');
2604 if (i != -1) {
Mandy Chungd3ccd202012-11-02 16:50:23 -07002605 // skip the package access check on a proxy class in default proxy package
2606 String pkg = name.substring(0, i);
Mandy Chung3a6de962013-04-17 15:04:59 -07002607 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
Mandy Chungd3ccd202012-11-02 16:50:23 -07002608 s.checkPackageAccess(pkg);
2609 }
J. Duke319a3b92007-12-01 00:00:00 +00002610 }
2611 }
Mandy Chungd3ccd202012-11-02 16:50:23 -07002612 // check package access on the proxy interfaces
2613 if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
2614 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
2615 }
J. Duke319a3b92007-12-01 00:00:00 +00002616 }
2617 }
2618
2619 /**
2620 * Add a package name prefix if the name is not absolute Remove leading "/"
2621 * if name is absolute
2622 */
2623 private String resolveName(String name) {
2624 if (name == null) {
2625 return name;
2626 }
2627 if (!name.startsWith("/")) {
Joe Darcybd9e7da2009-10-06 13:31:41 -07002628 Class<?> c = this;
J. Duke319a3b92007-12-01 00:00:00 +00002629 while (c.isArray()) {
2630 c = c.getComponentType();
2631 }
2632 String baseName = c.getName();
2633 int index = baseName.lastIndexOf('.');
2634 if (index != -1) {
2635 name = baseName.substring(0, index).replace('.', '/')
2636 +"/"+name;
2637 }
2638 } else {
2639 name = name.substring(1);
2640 }
2641 return name;
2642 }
2643
2644 /**
Peter Levartb0d16762013-07-15 10:55:53 +02002645 * Atomic operations support.
2646 */
2647 private static class Atomic {
2648 // initialize Unsafe machinery here, since we need to call Class.class instance method
2649 // and have to avoid calling it in the static initializer of the Class class...
2650 private static final Unsafe unsafe = Unsafe.getUnsafe();
2651 // offset of Class.reflectionData instance field
2652 private static final long reflectionDataOffset;
2653 // offset of Class.annotationType instance field
2654 private static final long annotationTypeOffset;
Peter Levartc7759dc2013-09-19 16:14:13 +02002655 // offset of Class.annotationData instance field
2656 private static final long annotationDataOffset;
Peter Levartb0d16762013-07-15 10:55:53 +02002657
2658 static {
2659 Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches
2660 reflectionDataOffset = objectFieldOffset(fields, "reflectionData");
2661 annotationTypeOffset = objectFieldOffset(fields, "annotationType");
Peter Levartc7759dc2013-09-19 16:14:13 +02002662 annotationDataOffset = objectFieldOffset(fields, "annotationData");
Peter Levartb0d16762013-07-15 10:55:53 +02002663 }
2664
2665 private static long objectFieldOffset(Field[] fields, String fieldName) {
2666 Field field = searchFields(fields, fieldName);
2667 if (field == null) {
2668 throw new Error("No " + fieldName + " field found in java.lang.Class");
2669 }
2670 return unsafe.objectFieldOffset(field);
2671 }
2672
2673 static <T> boolean casReflectionData(Class<?> clazz,
2674 SoftReference<ReflectionData<T>> oldData,
2675 SoftReference<ReflectionData<T>> newData) {
2676 return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
2677 }
2678
2679 static <T> boolean casAnnotationType(Class<?> clazz,
2680 AnnotationType oldType,
2681 AnnotationType newType) {
2682 return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);
2683 }
Peter Levartc7759dc2013-09-19 16:14:13 +02002684
2685 static <T> boolean casAnnotationData(Class<?> clazz,
2686 AnnotationData oldData,
2687 AnnotationData newData) {
2688 return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData);
2689 }
Peter Levartb0d16762013-07-15 10:55:53 +02002690 }
2691
2692 /**
J. Duke319a3b92007-12-01 00:00:00 +00002693 * Reflection support.
2694 */
2695
2696 // Caches for certain reflective results
2697 private static boolean useCaches = true;
Peter Levarte9127732013-01-13 19:57:06 -05002698
2699 // reflection data that might get invalidated when JVM TI RedefineClasses() is called
Peter Levartc7759dc2013-09-19 16:14:13 +02002700 private static class ReflectionData<T> {
Peter Levarte9127732013-01-13 19:57:06 -05002701 volatile Field[] declaredFields;
2702 volatile Field[] publicFields;
2703 volatile Method[] declaredMethods;
2704 volatile Method[] publicMethods;
2705 volatile Constructor<T>[] declaredConstructors;
2706 volatile Constructor<T>[] publicConstructors;
2707 // Intermediate results for getFields and getMethods
2708 volatile Field[] declaredPublicFields;
2709 volatile Method[] declaredPublicMethods;
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +04002710 volatile Class<?>[] interfaces;
2711
Peter Levarte9127732013-01-13 19:57:06 -05002712 // Value of classRedefinedCount when we created this ReflectionData instance
2713 final int redefinedCount;
2714
2715 ReflectionData(int redefinedCount) {
2716 this.redefinedCount = redefinedCount;
2717 }
Peter Levarte9127732013-01-13 19:57:06 -05002718 }
2719
Martin Buchholza2f0fe32015-09-15 21:56:04 -07002720 private transient volatile SoftReference<ReflectionData<T>> reflectionData;
J. Duke319a3b92007-12-01 00:00:00 +00002721
2722 // Incremented by the VM on each call to JVM TI RedefineClasses()
2723 // that redefines this class or a superclass.
Claes Redestad5f1918e2015-12-21 20:54:00 +01002724 private transient volatile int classRedefinedCount;
J. Duke319a3b92007-12-01 00:00:00 +00002725
Peter Levarte9127732013-01-13 19:57:06 -05002726 // Lazily create and cache ReflectionData
2727 private ReflectionData<T> reflectionData() {
2728 SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2729 int classRedefinedCount = this.classRedefinedCount;
2730 ReflectionData<T> rd;
2731 if (useCaches &&
2732 reflectionData != null &&
2733 (rd = reflectionData.get()) != null &&
2734 rd.redefinedCount == classRedefinedCount) {
2735 return rd;
2736 }
2737 // else no SoftReference or cleared SoftReference or stale ReflectionData
2738 // -> create and replace new instance
2739 return newReflectionData(reflectionData, classRedefinedCount);
2740 }
J. Duke319a3b92007-12-01 00:00:00 +00002741
Peter Levarte9127732013-01-13 19:57:06 -05002742 private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2743 int classRedefinedCount) {
2744 if (!useCaches) return null;
J. Duke319a3b92007-12-01 00:00:00 +00002745
Peter Levarte9127732013-01-13 19:57:06 -05002746 while (true) {
2747 ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2748 // try to CAS it...
Peter Levartb0d16762013-07-15 10:55:53 +02002749 if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
Peter Levarte9127732013-01-13 19:57:06 -05002750 return rd;
2751 }
2752 // else retry
2753 oldReflectionData = this.reflectionData;
2754 classRedefinedCount = this.classRedefinedCount;
2755 if (oldReflectionData != null &&
2756 (rd = oldReflectionData.get()) != null &&
2757 rd.redefinedCount == classRedefinedCount) {
2758 return rd;
2759 }
J. Duke319a3b92007-12-01 00:00:00 +00002760 }
2761 }
2762
2763 // Generic signature handling
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +04002764 private native String getGenericSignature0();
J. Duke319a3b92007-12-01 00:00:00 +00002765
2766 // Generic info repository; lazily initialized
Martin Buchholza2f0fe32015-09-15 21:56:04 -07002767 private transient volatile ClassRepository genericInfo;
J. Duke319a3b92007-12-01 00:00:00 +00002768
2769 // accessor for factory
2770 private GenericsFactory getFactory() {
2771 // create scope and factory
2772 return CoreReflectionFactory.make(this, ClassScope.make(this));
2773 }
2774
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +04002775 // accessor for generic info repository;
2776 // generic info is lazily initialized
J. Duke319a3b92007-12-01 00:00:00 +00002777 private ClassRepository getGenericInfo() {
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +04002778 ClassRepository genericInfo = this.genericInfo;
J. Duke319a3b92007-12-01 00:00:00 +00002779 if (genericInfo == null) {
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +04002780 String signature = getGenericSignature0();
2781 if (signature == null) {
2782 genericInfo = ClassRepository.NONE;
2783 } else {
2784 genericInfo = ClassRepository.make(signature, getFactory());
2785 }
2786 this.genericInfo = genericInfo;
J. Duke319a3b92007-12-01 00:00:00 +00002787 }
Aleksey Shipilev9821ebc2013-06-17 16:28:22 +04002788 return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
J. Duke319a3b92007-12-01 00:00:00 +00002789 }
2790
2791 // Annotations handling
Peter Levartb0d16762013-07-15 10:55:53 +02002792 native byte[] getRawAnnotations();
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01002793 // Since 1.8
2794 native byte[] getRawTypeAnnotations();
2795 static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2796 return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2797 }
J. Duke319a3b92007-12-01 00:00:00 +00002798
2799 native ConstantPool getConstantPool();
2800
2801 //
2802 //
2803 // java.lang.reflect.Field handling
2804 //
2805 //
2806
2807 // Returns an array of "root" fields. These Field objects must NOT
2808 // be propagated to the outside world, but must instead be copied
2809 // via ReflectionFactory.copyField.
2810 private Field[] privateGetDeclaredFields(boolean publicOnly) {
2811 checkInitted();
Peter Levarte9127732013-01-13 19:57:06 -05002812 Field[] res;
2813 ReflectionData<T> rd = reflectionData();
2814 if (rd != null) {
2815 res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
J. Duke319a3b92007-12-01 00:00:00 +00002816 if (res != null) return res;
2817 }
2818 // No cached value available; request value from VM
2819 res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
Peter Levarte9127732013-01-13 19:57:06 -05002820 if (rd != null) {
J. Duke319a3b92007-12-01 00:00:00 +00002821 if (publicOnly) {
Peter Levarte9127732013-01-13 19:57:06 -05002822 rd.declaredPublicFields = res;
J. Duke319a3b92007-12-01 00:00:00 +00002823 } else {
Peter Levarte9127732013-01-13 19:57:06 -05002824 rd.declaredFields = res;
J. Duke319a3b92007-12-01 00:00:00 +00002825 }
2826 }
2827 return res;
2828 }
2829
2830 // Returns an array of "root" fields. These Field objects must NOT
2831 // be propagated to the outside world, but must instead be copied
2832 // via ReflectionFactory.copyField.
Martin Buchholz43410942008-03-10 15:07:09 -07002833 private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
J. Duke319a3b92007-12-01 00:00:00 +00002834 checkInitted();
Peter Levarte9127732013-01-13 19:57:06 -05002835 Field[] res;
2836 ReflectionData<T> rd = reflectionData();
2837 if (rd != null) {
2838 res = rd.publicFields;
J. Duke319a3b92007-12-01 00:00:00 +00002839 if (res != null) return res;
2840 }
2841
2842 // No cached value available; compute value recursively.
2843 // Traverse in correct order for getField().
Stuart Marks6e7cb442010-12-20 13:47:04 -08002844 List<Field> fields = new ArrayList<>();
J. Duke319a3b92007-12-01 00:00:00 +00002845 if (traversedInterfaces == null) {
Stuart Marks6e7cb442010-12-20 13:47:04 -08002846 traversedInterfaces = new HashSet<>();
J. Duke319a3b92007-12-01 00:00:00 +00002847 }
2848
2849 // Local fields
2850 Field[] tmp = privateGetDeclaredFields(true);
2851 addAll(fields, tmp);
2852
2853 // Direct superinterfaces, recursively
Martin Buchholz43410942008-03-10 15:07:09 -07002854 for (Class<?> c : getInterfaces()) {
J. Duke319a3b92007-12-01 00:00:00 +00002855 if (!traversedInterfaces.contains(c)) {
2856 traversedInterfaces.add(c);
2857 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2858 }
2859 }
2860
2861 // Direct superclass, recursively
2862 if (!isInterface()) {
Martin Buchholz43410942008-03-10 15:07:09 -07002863 Class<?> c = getSuperclass();
J. Duke319a3b92007-12-01 00:00:00 +00002864 if (c != null) {
2865 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2866 }
2867 }
2868
2869 res = new Field[fields.size()];
2870 fields.toArray(res);
Peter Levarte9127732013-01-13 19:57:06 -05002871 if (rd != null) {
2872 rd.publicFields = res;
J. Duke319a3b92007-12-01 00:00:00 +00002873 }
2874 return res;
2875 }
2876
Martin Buchholz43410942008-03-10 15:07:09 -07002877 private static void addAll(Collection<Field> c, Field[] o) {
Paul Sandoz51efd872014-01-27 14:29:37 +01002878 for (Field f : o) {
2879 c.add(f);
J. Duke319a3b92007-12-01 00:00:00 +00002880 }
2881 }
2882
2883
2884 //
2885 //
2886 // java.lang.reflect.Constructor handling
2887 //
2888 //
2889
2890 // Returns an array of "root" constructors. These Constructor
2891 // objects must NOT be propagated to the outside world, but must
2892 // instead be copied via ReflectionFactory.copyConstructor.
Martin Buchholz43410942008-03-10 15:07:09 -07002893 private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
J. Duke319a3b92007-12-01 00:00:00 +00002894 checkInitted();
Peter Levarte9127732013-01-13 19:57:06 -05002895 Constructor<T>[] res;
2896 ReflectionData<T> rd = reflectionData();
2897 if (rd != null) {
2898 res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
J. Duke319a3b92007-12-01 00:00:00 +00002899 if (res != null) return res;
2900 }
2901 // No cached value available; request value from VM
2902 if (isInterface()) {
Omair Majidd312aad2011-12-08 13:48:54 -05002903 @SuppressWarnings("unchecked")
2904 Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
2905 res = temporaryRes;
J. Duke319a3b92007-12-01 00:00:00 +00002906 } else {
2907 res = getDeclaredConstructors0(publicOnly);
2908 }
Peter Levarte9127732013-01-13 19:57:06 -05002909 if (rd != null) {
J. Duke319a3b92007-12-01 00:00:00 +00002910 if (publicOnly) {
Peter Levarte9127732013-01-13 19:57:06 -05002911 rd.publicConstructors = res;
J. Duke319a3b92007-12-01 00:00:00 +00002912 } else {
Peter Levarte9127732013-01-13 19:57:06 -05002913 rd.declaredConstructors = res;
J. Duke319a3b92007-12-01 00:00:00 +00002914 }
2915 }
2916 return res;
2917 }
2918
2919 //
2920 //
2921 // java.lang.reflect.Method handling
2922 //
2923 //
2924
2925 // Returns an array of "root" methods. These Method objects must NOT
2926 // be propagated to the outside world, but must instead be copied
2927 // via ReflectionFactory.copyMethod.
2928 private Method[] privateGetDeclaredMethods(boolean publicOnly) {
2929 checkInitted();
Peter Levarte9127732013-01-13 19:57:06 -05002930 Method[] res;
2931 ReflectionData<T> rd = reflectionData();
2932 if (rd != null) {
2933 res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
J. Duke319a3b92007-12-01 00:00:00 +00002934 if (res != null) return res;
2935 }
2936 // No cached value available; request value from VM
2937 res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
Peter Levarte9127732013-01-13 19:57:06 -05002938 if (rd != null) {
J. Duke319a3b92007-12-01 00:00:00 +00002939 if (publicOnly) {
Peter Levarte9127732013-01-13 19:57:06 -05002940 rd.declaredPublicMethods = res;
J. Duke319a3b92007-12-01 00:00:00 +00002941 } else {
Peter Levarte9127732013-01-13 19:57:06 -05002942 rd.declaredMethods = res;
J. Duke319a3b92007-12-01 00:00:00 +00002943 }
2944 }
2945 return res;
2946 }
2947
2948 static class MethodArray {
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02002949 // Don't add or remove methods except by add() or remove() calls.
J. Duke319a3b92007-12-01 00:00:00 +00002950 private Method[] methods;
2951 private int length;
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02002952 private int defaults;
J. Duke319a3b92007-12-01 00:00:00 +00002953
2954 MethodArray() {
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02002955 this(20);
2956 }
2957
2958 MethodArray(int initialSize) {
2959 if (initialSize < 2)
2960 throw new IllegalArgumentException("Size should be 2 or more");
2961
2962 methods = new Method[initialSize];
J. Duke319a3b92007-12-01 00:00:00 +00002963 length = 0;
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02002964 defaults = 0;
2965 }
2966
2967 boolean hasDefaults() {
2968 return defaults != 0;
J. Duke319a3b92007-12-01 00:00:00 +00002969 }
2970
2971 void add(Method m) {
2972 if (length == methods.length) {
2973 methods = Arrays.copyOf(methods, 2 * methods.length);
2974 }
2975 methods[length++] = m;
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02002976
2977 if (m != null && m.isDefault())
2978 defaults++;
J. Duke319a3b92007-12-01 00:00:00 +00002979 }
2980
2981 void addAll(Method[] ma) {
Paul Sandoz51efd872014-01-27 14:29:37 +01002982 for (Method m : ma) {
2983 add(m);
J. Duke319a3b92007-12-01 00:00:00 +00002984 }
2985 }
2986
2987 void addAll(MethodArray ma) {
2988 for (int i = 0; i < ma.length(); i++) {
2989 add(ma.get(i));
2990 }
2991 }
2992
2993 void addIfNotPresent(Method newMethod) {
2994 for (int i = 0; i < length; i++) {
2995 Method m = methods[i];
2996 if (m == newMethod || (m != null && m.equals(newMethod))) {
2997 return;
2998 }
2999 }
3000 add(newMethod);
3001 }
3002
3003 void addAllIfNotPresent(MethodArray newMethods) {
3004 for (int i = 0; i < newMethods.length(); i++) {
3005 Method m = newMethods.get(i);
3006 if (m != null) {
3007 addIfNotPresent(m);
3008 }
3009 }
3010 }
3011
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003012 /* Add Methods declared in an interface to this MethodArray.
3013 * Static methods declared in interfaces are not inherited.
3014 */
3015 void addInterfaceMethods(Method[] methods) {
Joel Borggrén-Franck415ea442013-10-22 10:34:12 +02003016 for (Method candidate : methods) {
3017 if (!Modifier.isStatic(candidate.getModifiers())) {
3018 add(candidate);
3019 }
3020 }
3021 }
3022
J. Duke319a3b92007-12-01 00:00:00 +00003023 int length() {
3024 return length;
3025 }
3026
3027 Method get(int i) {
3028 return methods[i];
3029 }
3030
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003031 Method getFirst() {
3032 for (Method m : methods)
3033 if (m != null)
3034 return m;
3035 return null;
3036 }
3037
3038 void removeByNameAndDescriptor(Method toRemove) {
J. Duke319a3b92007-12-01 00:00:00 +00003039 for (int i = 0; i < length; i++) {
3040 Method m = methods[i];
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003041 if (m != null && matchesNameAndDescriptor(m, toRemove)) {
3042 remove(i);
J. Duke319a3b92007-12-01 00:00:00 +00003043 }
3044 }
3045 }
3046
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003047 private void remove(int i) {
3048 if (methods[i] != null && methods[i].isDefault())
3049 defaults--;
Alan Batemandb4d3832016-03-17 19:04:16 +00003050 methods[i] = null;
3051 }
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003052
3053 private boolean matchesNameAndDescriptor(Method m1, Method m2) {
3054 return m1.getReturnType() == m2.getReturnType() &&
3055 m1.getName() == m2.getName() && // name is guaranteed to be interned
3056 arrayContentsEq(m1.getParameterTypes(),
3057 m2.getParameterTypes());
Alan Batemandb4d3832016-03-17 19:04:16 +00003058 }
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003059
J. Duke319a3b92007-12-01 00:00:00 +00003060 void compactAndTrim() {
3061 int newPos = 0;
3062 // Get rid of null slots
3063 for (int pos = 0; pos < length; pos++) {
3064 Method m = methods[pos];
3065 if (m != null) {
3066 if (pos != newPos) {
3067 methods[newPos] = m;
3068 }
3069 newPos++;
3070 }
3071 }
3072 if (newPos != methods.length) {
3073 methods = Arrays.copyOf(methods, newPos);
3074 }
3075 }
3076
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003077 /* Removes all Methods from this MethodArray that have a more specific
3078 * default Method in this MethodArray.
3079 *
3080 * Users of MethodArray are responsible for pruning Methods that have
3081 * a more specific <em>concrete</em> Method.
3082 */
3083 void removeLessSpecifics() {
3084 if (!hasDefaults())
3085 return;
3086
3087 for (int i = 0; i < length; i++) {
3088 Method m = get(i);
3089 if (m == null || !m.isDefault())
3090 continue;
3091
3092 for (int j = 0; j < length; j++) {
3093 if (i == j)
3094 continue;
3095
3096 Method candidate = get(j);
3097 if (candidate == null)
3098 continue;
3099
3100 if (!matchesNameAndDescriptor(m, candidate))
3101 continue;
3102
3103 if (hasMoreSpecificClass(m, candidate))
3104 remove(j);
3105 }
3106 }
3107 }
3108
J. Duke319a3b92007-12-01 00:00:00 +00003109 Method[] getArray() {
3110 return methods;
3111 }
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003112
3113 // Returns true if m1 is more specific than m2
3114 static boolean hasMoreSpecificClass(Method m1, Method m2) {
3115 Class<?> m1Class = m1.getDeclaringClass();
3116 Class<?> m2Class = m2.getDeclaringClass();
3117 return m1Class != m2Class && m2Class.isAssignableFrom(m1Class);
3118 }
J. Duke319a3b92007-12-01 00:00:00 +00003119 }
3120
3121
3122 // Returns an array of "root" methods. These Method objects must NOT
3123 // be propagated to the outside world, but must instead be copied
3124 // via ReflectionFactory.copyMethod.
3125 private Method[] privateGetPublicMethods() {
3126 checkInitted();
Peter Levarte9127732013-01-13 19:57:06 -05003127 Method[] res;
3128 ReflectionData<T> rd = reflectionData();
3129 if (rd != null) {
3130 res = rd.publicMethods;
J. Duke319a3b92007-12-01 00:00:00 +00003131 if (res != null) return res;
3132 }
3133
3134 // No cached value available; compute value recursively.
3135 // Start by fetching public declared methods
3136 MethodArray methods = new MethodArray();
3137 {
Peter Levarte9127732013-01-13 19:57:06 -05003138 Method[] tmp = privateGetDeclaredMethods(true);
J. Duke319a3b92007-12-01 00:00:00 +00003139 methods.addAll(tmp);
3140 }
3141 // Now recur over superclass and direct superinterfaces.
3142 // Go over superinterfaces first so we can more easily filter
3143 // out concrete implementations inherited from superclasses at
3144 // the end.
3145 MethodArray inheritedMethods = new MethodArray();
Paul Sandoz51efd872014-01-27 14:29:37 +01003146 for (Class<?> i : getInterfaces()) {
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003147 inheritedMethods.addInterfaceMethods(i.privateGetPublicMethods());
J. Duke319a3b92007-12-01 00:00:00 +00003148 }
3149 if (!isInterface()) {
Joe Darcybd9e7da2009-10-06 13:31:41 -07003150 Class<?> c = getSuperclass();
J. Duke319a3b92007-12-01 00:00:00 +00003151 if (c != null) {
3152 MethodArray supers = new MethodArray();
3153 supers.addAll(c.privateGetPublicMethods());
3154 // Filter out concrete implementations of any
3155 // interface methods
3156 for (int i = 0; i < supers.length(); i++) {
3157 Method m = supers.get(i);
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003158 if (m != null &&
3159 !Modifier.isAbstract(m.getModifiers()) &&
3160 !m.isDefault()) {
3161 inheritedMethods.removeByNameAndDescriptor(m);
J. Duke319a3b92007-12-01 00:00:00 +00003162 }
3163 }
3164 // Insert superclass's inherited methods before
3165 // superinterfaces' to satisfy getMethod's search
3166 // order
3167 supers.addAll(inheritedMethods);
3168 inheritedMethods = supers;
3169 }
3170 }
3171 // Filter out all local methods from inherited ones
3172 for (int i = 0; i < methods.length(); i++) {
3173 Method m = methods.get(i);
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003174 inheritedMethods.removeByNameAndDescriptor(m);
J. Duke319a3b92007-12-01 00:00:00 +00003175 }
3176 methods.addAllIfNotPresent(inheritedMethods);
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003177 methods.removeLessSpecifics();
J. Duke319a3b92007-12-01 00:00:00 +00003178 methods.compactAndTrim();
3179 res = methods.getArray();
Peter Levarte9127732013-01-13 19:57:06 -05003180 if (rd != null) {
3181 rd.publicMethods = res;
J. Duke319a3b92007-12-01 00:00:00 +00003182 }
3183 return res;
3184 }
3185
3186
3187 //
3188 // Helpers for fetchers of one field, method, or constructor
3189 //
3190
Peter Levarte9127732013-01-13 19:57:06 -05003191 private static Field searchFields(Field[] fields, String name) {
J. Duke319a3b92007-12-01 00:00:00 +00003192 String internedName = name.intern();
Paul Sandoz51efd872014-01-27 14:29:37 +01003193 for (Field field : fields) {
3194 if (field.getName() == internedName) {
3195 return getReflectionFactory().copyField(field);
J. Duke319a3b92007-12-01 00:00:00 +00003196 }
3197 }
3198 return null;
3199 }
3200
3201 private Field getField0(String name) throws NoSuchFieldException {
3202 // Note: the intent is that the search algorithm this routine
3203 // uses be equivalent to the ordering imposed by
3204 // privateGetPublicFields(). It fetches only the declared
3205 // public fields for each class, however, to reduce the number
3206 // of Field objects which have to be created for the common
3207 // case where the field being requested is declared in the
3208 // class which is being queried.
Peter Levarte9127732013-01-13 19:57:06 -05003209 Field res;
J. Duke319a3b92007-12-01 00:00:00 +00003210 // Search declared public fields
3211 if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3212 return res;
3213 }
3214 // Direct superinterfaces, recursively
Joe Darcybd9e7da2009-10-06 13:31:41 -07003215 Class<?>[] interfaces = getInterfaces();
Paul Sandoz51efd872014-01-27 14:29:37 +01003216 for (Class<?> c : interfaces) {
J. Duke319a3b92007-12-01 00:00:00 +00003217 if ((res = c.getField0(name)) != null) {
3218 return res;
3219 }
3220 }
3221 // Direct superclass, recursively
3222 if (!isInterface()) {
Joe Darcybd9e7da2009-10-06 13:31:41 -07003223 Class<?> c = getSuperclass();
J. Duke319a3b92007-12-01 00:00:00 +00003224 if (c != null) {
3225 if ((res = c.getField0(name)) != null) {
3226 return res;
3227 }
3228 }
3229 }
3230 return null;
3231 }
3232
3233 private static Method searchMethods(Method[] methods,
3234 String name,
Joe Darcybd9e7da2009-10-06 13:31:41 -07003235 Class<?>[] parameterTypes)
J. Duke319a3b92007-12-01 00:00:00 +00003236 {
3237 Method res = null;
3238 String internedName = name.intern();
Paul Sandoz51efd872014-01-27 14:29:37 +01003239 for (Method m : methods) {
J. Duke319a3b92007-12-01 00:00:00 +00003240 if (m.getName() == internedName
3241 && arrayContentsEq(parameterTypes, m.getParameterTypes())
3242 && (res == null
3243 || res.getReturnType().isAssignableFrom(m.getReturnType())))
3244 res = m;
3245 }
3246
3247 return (res == null ? res : getReflectionFactory().copyMethod(res));
3248 }
3249
Joel Borggrén-Franck415ea442013-10-22 10:34:12 +02003250 private Method getMethod0(String name, Class<?>[] parameterTypes, boolean includeStaticMethods) {
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003251 MethodArray interfaceCandidates = new MethodArray(2);
3252 Method res = privateGetMethodRecursive(name, parameterTypes, includeStaticMethods, interfaceCandidates);
3253 if (res != null)
3254 return res;
3255
3256 // Not found on class or superclass directly
3257 interfaceCandidates.removeLessSpecifics();
3258 return interfaceCandidates.getFirst(); // may be null
3259 }
3260
3261 private Method privateGetMethodRecursive(String name,
3262 Class<?>[] parameterTypes,
3263 boolean includeStaticMethods,
3264 MethodArray allInterfaceCandidates) {
J. Duke319a3b92007-12-01 00:00:00 +00003265 // Note: the intent is that the search algorithm this routine
3266 // uses be equivalent to the ordering imposed by
3267 // privateGetPublicMethods(). It fetches only the declared
3268 // public methods for each class, however, to reduce the
3269 // number of Method objects which have to be created for the
3270 // common case where the method being requested is declared in
3271 // the class which is being queried.
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003272 //
3273 // Due to default methods, unless a method is found on a superclass,
3274 // methods declared in any superinterface needs to be considered.
3275 // Collect all candidates declared in superinterfaces in {@code
3276 // allInterfaceCandidates} and select the most specific if no match on
3277 // a superclass is found.
3278
3279 // Must _not_ return root methods
Peter Levarte9127732013-01-13 19:57:06 -05003280 Method res;
J. Duke319a3b92007-12-01 00:00:00 +00003281 // Search declared public methods
3282 if ((res = searchMethods(privateGetDeclaredMethods(true),
3283 name,
3284 parameterTypes)) != null) {
Joel Borggrén-Franck415ea442013-10-22 10:34:12 +02003285 if (includeStaticMethods || !Modifier.isStatic(res.getModifiers()))
3286 return res;
J. Duke319a3b92007-12-01 00:00:00 +00003287 }
3288 // Search superclass's methods
3289 if (!isInterface()) {
Joe Darcybd9e7da2009-10-06 13:31:41 -07003290 Class<? super T> c = getSuperclass();
J. Duke319a3b92007-12-01 00:00:00 +00003291 if (c != null) {
Joel Borggrén-Franck415ea442013-10-22 10:34:12 +02003292 if ((res = c.getMethod0(name, parameterTypes, true)) != null) {
J. Duke319a3b92007-12-01 00:00:00 +00003293 return res;
3294 }
3295 }
3296 }
3297 // Search superinterfaces' methods
Joe Darcybd9e7da2009-10-06 13:31:41 -07003298 Class<?>[] interfaces = getInterfaces();
Joel Borggrén-Franck415ea442013-10-22 10:34:12 +02003299 for (Class<?> c : interfaces)
3300 if ((res = c.getMethod0(name, parameterTypes, false)) != null)
Joel Borggrén-Franck64459802014-06-10 14:40:20 +02003301 allInterfaceCandidates.add(res);
J. Duke319a3b92007-12-01 00:00:00 +00003302 // Not found
3303 return null;
3304 }
3305
Joe Darcybd9e7da2009-10-06 13:31:41 -07003306 private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
J. Duke319a3b92007-12-01 00:00:00 +00003307 int which) throws NoSuchMethodException
3308 {
Martin Buchholz43410942008-03-10 15:07:09 -07003309 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3310 for (Constructor<T> constructor : constructors) {
J. Duke319a3b92007-12-01 00:00:00 +00003311 if (arrayContentsEq(parameterTypes,
Martin Buchholz43410942008-03-10 15:07:09 -07003312 constructor.getParameterTypes())) {
3313 return getReflectionFactory().copyConstructor(constructor);
J. Duke319a3b92007-12-01 00:00:00 +00003314 }
3315 }
3316 throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
3317 }
3318
3319 //
3320 // Other helpers and base implementation
3321 //
3322
3323 private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3324 if (a1 == null) {
3325 return a2 == null || a2.length == 0;
3326 }
3327
3328 if (a2 == null) {
3329 return a1.length == 0;
3330 }
3331
3332 if (a1.length != a2.length) {
3333 return false;
3334 }
3335
3336 for (int i = 0; i < a1.length; i++) {
3337 if (a1[i] != a2[i]) {
3338 return false;
3339 }
3340 }
3341
3342 return true;
3343 }
3344
3345 private static Field[] copyFields(Field[] arg) {
3346 Field[] out = new Field[arg.length];
3347 ReflectionFactory fact = getReflectionFactory();
3348 for (int i = 0; i < arg.length; i++) {
3349 out[i] = fact.copyField(arg[i]);
3350 }
3351 return out;
3352 }
3353
3354 private static Method[] copyMethods(Method[] arg) {
3355 Method[] out = new Method[arg.length];
3356 ReflectionFactory fact = getReflectionFactory();
3357 for (int i = 0; i < arg.length; i++) {
3358 out[i] = fact.copyMethod(arg[i]);
3359 }
3360 return out;
3361 }
3362
Martin Buchholz43410942008-03-10 15:07:09 -07003363 private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3364 Constructor<U>[] out = arg.clone();
J. Duke319a3b92007-12-01 00:00:00 +00003365 ReflectionFactory fact = getReflectionFactory();
Martin Buchholz43410942008-03-10 15:07:09 -07003366 for (int i = 0; i < out.length; i++) {
3367 out[i] = fact.copyConstructor(out[i]);
J. Duke319a3b92007-12-01 00:00:00 +00003368 }
3369 return out;
3370 }
3371
3372 private native Field[] getDeclaredFields0(boolean publicOnly);
3373 private native Method[] getDeclaredMethods0(boolean publicOnly);
Martin Buchholz43410942008-03-10 15:07:09 -07003374 private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
Joe Darcybd9e7da2009-10-06 13:31:41 -07003375 private native Class<?>[] getDeclaredClasses0();
J. Duke319a3b92007-12-01 00:00:00 +00003376
Joe Darcybd9e7da2009-10-06 13:31:41 -07003377 private static String argumentTypesToString(Class<?>[] argTypes) {
Ivan Gerasimove164c862014-08-27 22:08:19 +04003378 StringJoiner sj = new StringJoiner(", ", "(", ")");
J. Duke319a3b92007-12-01 00:00:00 +00003379 if (argTypes != null) {
3380 for (int i = 0; i < argTypes.length; i++) {
Joe Darcybd9e7da2009-10-06 13:31:41 -07003381 Class<?> c = argTypes[i];
Ivan Gerasimove164c862014-08-27 22:08:19 +04003382 sj.add((c == null) ? "null" : c.getName());
J. Duke319a3b92007-12-01 00:00:00 +00003383 }
3384 }
Ivan Gerasimove164c862014-08-27 22:08:19 +04003385 return sj.toString();
J. Duke319a3b92007-12-01 00:00:00 +00003386 }
3387
3388 /** use serialVersionUID from JDK 1.1 for interoperability */
3389 private static final long serialVersionUID = 3206093459760846163L;
3390
3391
3392 /**
3393 * Class Class is special cased within the Serialization Stream Protocol.
3394 *
3395 * A Class instance is written initially into an ObjectOutputStream in the
3396 * following format:
3397 * <pre>
3398 * {@code TC_CLASS} ClassDescriptor
3399 * A ClassDescriptor is a special cased serialization of
3400 * a {@code java.io.ObjectStreamClass} instance.
3401 * </pre>
3402 * A new handle is generated for the initial time the class descriptor
3403 * is written into the stream. Future references to the class descriptor
3404 * are written as references to the initial class descriptor instance.
3405 *
3406 * @see java.io.ObjectStreamClass
3407 */
3408 private static final ObjectStreamField[] serialPersistentFields =
3409 new ObjectStreamField[0];
3410
3411
3412 /**
3413 * Returns the assertion status that would be assigned to this
3414 * class if it were to be initialized at the time this method is invoked.
3415 * If this class has had its assertion status set, the most recent
3416 * setting will be returned; otherwise, if any package default assertion
3417 * status pertains to this class, the most recent setting for the most
3418 * specific pertinent package default assertion status is returned;
3419 * otherwise, if this class is not a system class (i.e., it has a
3420 * class loader) its class loader's default assertion status is returned;
3421 * otherwise, the system class default assertion status is returned.
3422 * <p>
3423 * Few programmers will have any need for this method; it is provided
3424 * for the benefit of the JRE itself. (It allows a class to determine at
3425 * the time that it is initialized whether assertions should be enabled.)
3426 * Note that this method is not guaranteed to return the actual
3427 * assertion status that was (or will be) associated with the specified
3428 * class when it was (or will be) initialized.
3429 *
3430 * @return the desired assertion status of the specified class.
3431 * @see java.lang.ClassLoader#setClassAssertionStatus
3432 * @see java.lang.ClassLoader#setPackageAssertionStatus
3433 * @see java.lang.ClassLoader#setDefaultAssertionStatus
3434 * @since 1.4
3435 */
3436 public boolean desiredAssertionStatus() {
3437 ClassLoader loader = getClassLoader();
3438 // If the loader is null this is a system class, so ask the VM
3439 if (loader == null)
3440 return desiredAssertionStatus0(this);
3441
Valerie Pengc10f5932009-04-06 18:46:20 -07003442 // If the classloader has been initialized with the assertion
3443 // directives, ask it. Otherwise, ask the VM.
3444 synchronized(loader.assertionLock) {
3445 if (loader.classAssertionStatus != null) {
3446 return loader.desiredAssertionStatus(getName());
3447 }
J. Duke319a3b92007-12-01 00:00:00 +00003448 }
Valerie Pengc10f5932009-04-06 18:46:20 -07003449 return desiredAssertionStatus0(this);
J. Duke319a3b92007-12-01 00:00:00 +00003450 }
3451
3452 // Retrieves the desired assertion status of this class from the VM
Joe Darcybd9e7da2009-10-06 13:31:41 -07003453 private static native boolean desiredAssertionStatus0(Class<?> clazz);
J. Duke319a3b92007-12-01 00:00:00 +00003454
3455 /**
3456 * Returns true if and only if this class was declared as an enum in the
3457 * source code.
3458 *
3459 * @return true if and only if this class was declared as an enum in the
3460 * source code
3461 * @since 1.5
3462 */
3463 public boolean isEnum() {
3464 // An enum must both directly extend java.lang.Enum and have
3465 // the ENUM bit set; classes for specialized enum constants
3466 // don't do the former.
3467 return (this.getModifiers() & ENUM) != 0 &&
3468 this.getSuperclass() == java.lang.Enum.class;
3469 }
3470
3471 // Fetches the factory for reflective objects
3472 private static ReflectionFactory getReflectionFactory() {
3473 if (reflectionFactory == null) {
Martin Buchholz43410942008-03-10 15:07:09 -07003474 reflectionFactory =
J. Duke319a3b92007-12-01 00:00:00 +00003475 java.security.AccessController.doPrivileged
3476 (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
3477 }
3478 return reflectionFactory;
3479 }
3480 private static ReflectionFactory reflectionFactory;
3481
3482 // To be able to query system properties as soon as they're available
3483 private static boolean initted = false;
3484 private static void checkInitted() {
3485 if (initted) return;
Joe Darcyd1122152015-04-23 09:32:35 -07003486 AccessController.doPrivileged(new PrivilegedAction<>() {
Martin Buchholz43410942008-03-10 15:07:09 -07003487 public Void run() {
J. Duke319a3b92007-12-01 00:00:00 +00003488 // Tests to ensure the system properties table is fully
3489 // initialized. This is needed because reflection code is
3490 // called very early in the initialization process (before
3491 // command-line arguments have been parsed and therefore
3492 // these user-settable properties installed.) We assume that
3493 // if System.out is non-null then the System class has been
3494 // fully initialized and that the bulk of the startup code
3495 // has been run.
3496
3497 if (System.out == null) {
3498 // java.lang.System not yet fully initialized
3499 return null;
3500 }
3501
Mike Duigou80af4652011-08-04 08:53:16 -07003502 // Doesn't use Boolean.getBoolean to avoid class init.
J. Duke319a3b92007-12-01 00:00:00 +00003503 String val =
3504 System.getProperty("sun.reflect.noCaches");
3505 if (val != null && val.equals("true")) {
3506 useCaches = false;
3507 }
3508
3509 initted = true;
3510 return null;
3511 }
3512 });
3513 }
3514
3515 /**
3516 * Returns the elements of this enum class or null if this
3517 * Class object does not represent an enum type.
3518 *
3519 * @return an array containing the values comprising the enum class
3520 * represented by this Class object in the order they're
3521 * declared, or null if this Class object does not
3522 * represent an enum type
3523 * @since 1.5
3524 */
3525 public T[] getEnumConstants() {
3526 T[] values = getEnumConstantsShared();
3527 return (values != null) ? values.clone() : null;
3528 }
3529
3530 /**
3531 * Returns the elements of this enum class or null if this
3532 * Class object does not represent an enum type;
Martin Buchholz43410942008-03-10 15:07:09 -07003533 * identical to getEnumConstants except that the result is
3534 * uncloned, cached, and shared by all callers.
J. Duke319a3b92007-12-01 00:00:00 +00003535 */
3536 T[] getEnumConstantsShared() {
Claes Redestad5f1918e2015-12-21 20:54:00 +01003537 T[] constants = enumConstants;
3538 if (constants == null) {
J. Duke319a3b92007-12-01 00:00:00 +00003539 if (!isEnum()) return null;
3540 try {
3541 final Method values = getMethod("values");
Martin Buchholz43410942008-03-10 15:07:09 -07003542 java.security.AccessController.doPrivileged(
Joe Darcyd1122152015-04-23 09:32:35 -07003543 new java.security.PrivilegedAction<>() {
Martin Buchholz43410942008-03-10 15:07:09 -07003544 public Void run() {
J. Duke319a3b92007-12-01 00:00:00 +00003545 values.setAccessible(true);
3546 return null;
3547 }
3548 });
Omair Majidd312aad2011-12-08 13:48:54 -05003549 @SuppressWarnings("unchecked")
3550 T[] temporaryConstants = (T[])values.invoke(null);
Claes Redestad5f1918e2015-12-21 20:54:00 +01003551 enumConstants = constants = temporaryConstants;
J. Duke319a3b92007-12-01 00:00:00 +00003552 }
3553 // These can happen when users concoct enum-like classes
3554 // that don't comply with the enum spec.
Joe Darcy2aa1b6d2011-08-08 09:07:43 -07003555 catch (InvocationTargetException | NoSuchMethodException |
3556 IllegalAccessException ex) { return null; }
J. Duke319a3b92007-12-01 00:00:00 +00003557 }
Claes Redestad5f1918e2015-12-21 20:54:00 +01003558 return constants;
J. Duke319a3b92007-12-01 00:00:00 +00003559 }
Claes Redestad5f1918e2015-12-21 20:54:00 +01003560 private transient volatile T[] enumConstants;
J. Duke319a3b92007-12-01 00:00:00 +00003561
3562 /**
3563 * Returns a map from simple name to enum constant. This package-private
3564 * method is used internally by Enum to implement
Alan Bateman9b8e06e2012-10-01 15:36:57 +01003565 * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
J. Duke319a3b92007-12-01 00:00:00 +00003566 * efficiently. Note that the map is returned by this method is
3567 * created lazily on first use. Typically it won't ever get created.
3568 */
3569 Map<String, T> enumConstantDirectory() {
Claes Redestad5f1918e2015-12-21 20:54:00 +01003570 Map<String, T> directory = enumConstantDirectory;
3571 if (directory == null) {
J. Duke319a3b92007-12-01 00:00:00 +00003572 T[] universe = getEnumConstantsShared();
3573 if (universe == null)
3574 throw new IllegalArgumentException(
3575 getName() + " is not an enum type");
Claes Redestad5f1918e2015-12-21 20:54:00 +01003576 directory = new HashMap<>(2 * universe.length);
3577 for (T constant : universe) {
3578 directory.put(((Enum<?>)constant).name(), constant);
3579 }
3580 enumConstantDirectory = directory;
J. Duke319a3b92007-12-01 00:00:00 +00003581 }
Claes Redestad5f1918e2015-12-21 20:54:00 +01003582 return directory;
J. Duke319a3b92007-12-01 00:00:00 +00003583 }
Claes Redestad5f1918e2015-12-21 20:54:00 +01003584 private transient volatile Map<String, T> enumConstantDirectory;
J. Duke319a3b92007-12-01 00:00:00 +00003585
3586 /**
3587 * Casts an object to the class or interface represented
3588 * by this {@code Class} object.
3589 *
3590 * @param obj the object to be cast
3591 * @return the object after casting, or null if obj is null
3592 *
3593 * @throws ClassCastException if the object is not
3594 * null and is not assignable to the type T.
3595 *
3596 * @since 1.5
3597 */
Omair Majidd312aad2011-12-08 13:48:54 -05003598 @SuppressWarnings("unchecked")
Zoltan Majo94d36642015-07-03 07:23:45 +02003599 @HotSpotIntrinsicCandidate
J. Duke319a3b92007-12-01 00:00:00 +00003600 public T cast(Object obj) {
3601 if (obj != null && !isInstance(obj))
3602 throw new ClassCastException(cannotCastMsg(obj));
3603 return (T) obj;
3604 }
3605
3606 private String cannotCastMsg(Object obj) {
3607 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3608 }
3609
3610 /**
3611 * Casts this {@code Class} object to represent a subclass of the class
Martin Desruisseauxf6f5a142011-11-10 11:41:27 -05003612 * represented by the specified class object. Checks that the cast
J. Duke319a3b92007-12-01 00:00:00 +00003613 * is valid, and throws a {@code ClassCastException} if it is not. If
3614 * this method succeeds, it always returns a reference to this class object.
3615 *
3616 * <p>This method is useful when a client needs to "narrow" the type of
3617 * a {@code Class} object to pass it to an API that restricts the
3618 * {@code Class} objects that it is willing to accept. A cast would
3619 * generate a compile-time warning, as the correctness of the cast
3620 * could not be checked at runtime (because generic types are implemented
3621 * by erasure).
3622 *
Joe Darcye751cc72013-06-24 23:40:31 -07003623 * @param <U> the type to cast this class object to
3624 * @param clazz the class of the type to cast this class object to
J. Duke319a3b92007-12-01 00:00:00 +00003625 * @return this {@code Class} object, cast to represent a subclass of
3626 * the specified class object.
3627 * @throws ClassCastException if this {@code Class} object does not
3628 * represent a subclass of the specified class (here "subclass" includes
3629 * the class itself).
3630 * @since 1.5
3631 */
Omair Majidd312aad2011-12-08 13:48:54 -05003632 @SuppressWarnings("unchecked")
J. Duke319a3b92007-12-01 00:00:00 +00003633 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3634 if (clazz.isAssignableFrom(this))
3635 return (Class<? extends U>) this;
3636 else
3637 throw new ClassCastException(this.toString());
3638 }
3639
3640 /**
3641 * @throws NullPointerException {@inheritDoc}
3642 * @since 1.5
3643 */
Joel Borggrén-Franck34e17262013-01-31 10:10:34 +01003644 @SuppressWarnings("unchecked")
J. Duke319a3b92007-12-01 00:00:00 +00003645 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
Joel Borggrén-Franck36464f42012-11-28 09:21:37 -08003646 Objects.requireNonNull(annotationClass);
J. Duke319a3b92007-12-01 00:00:00 +00003647
Peter Levartc7759dc2013-09-19 16:14:13 +02003648 return (A) annotationData().annotations.get(annotationClass);
J. Duke319a3b92007-12-01 00:00:00 +00003649 }
3650
3651 /**
Joe Darcybc576242013-03-04 19:42:56 -08003652 * {@inheritDoc}
3653 * @throws NullPointerException {@inheritDoc}
3654 * @since 1.5
3655 */
3656 @Override
3657 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
Joe Darcy7c644b02013-05-22 20:03:45 -07003658 return GenericDeclaration.super.isAnnotationPresent(annotationClass);
Joe Darcybc576242013-03-04 19:42:56 -08003659 }
3660
3661 /**
J. Duke319a3b92007-12-01 00:00:00 +00003662 * @throws NullPointerException {@inheritDoc}
Joel Borggrén-Franck36464f42012-11-28 09:21:37 -08003663 * @since 1.8
3664 */
Joel Borggrén-Francke0eba882013-02-13 10:36:36 +01003665 @Override
3666 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
Joel Borggrén-Franck36464f42012-11-28 09:21:37 -08003667 Objects.requireNonNull(annotationClass);
3668
Andreas Lundblad24b64e82013-10-22 12:35:27 +02003669 AnnotationData annotationData = annotationData();
3670 return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
Andreas Lundblad5db9cc72013-10-24 18:52:13 +02003671 this,
Andreas Lundblad24b64e82013-10-22 12:35:27 +02003672 annotationClass);
Joel Borggrén-Franck36464f42012-11-28 09:21:37 -08003673 }
J. Duke319a3b92007-12-01 00:00:00 +00003674
J. Duke319a3b92007-12-01 00:00:00 +00003675 /**
3676 * @since 1.5
3677 */
3678 public Annotation[] getAnnotations() {
Peter Levartc7759dc2013-09-19 16:14:13 +02003679 return AnnotationParser.toArray(annotationData().annotations);
Joel Borggrén-Franck36464f42012-11-28 09:21:37 -08003680 }
3681
3682 /**
3683 * @throws NullPointerException {@inheritDoc}
3684 * @since 1.8
3685 */
Joel Borggrén-Francke0eba882013-02-13 10:36:36 +01003686 @Override
Joel Borggrén-Franck34e17262013-01-31 10:10:34 +01003687 @SuppressWarnings("unchecked")
Joel Borggrén-Franck36464f42012-11-28 09:21:37 -08003688 public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3689 Objects.requireNonNull(annotationClass);
3690
Peter Levartc7759dc2013-09-19 16:14:13 +02003691 return (A) annotationData().declaredAnnotations.get(annotationClass);
Joel Borggrén-Franck36464f42012-11-28 09:21:37 -08003692 }
3693
3694 /**
3695 * @throws NullPointerException {@inheritDoc}
3696 * @since 1.8
3697 */
Joel Borggrén-Francke0eba882013-02-13 10:36:36 +01003698 @Override
3699 public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
Joel Borggrén-Franck36464f42012-11-28 09:21:37 -08003700 Objects.requireNonNull(annotationClass);
3701
Andreas Lundblad24b64e82013-10-22 12:35:27 +02003702 return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
3703 annotationClass);
J. Duke319a3b92007-12-01 00:00:00 +00003704 }
3705
3706 /**
3707 * @since 1.5
3708 */
3709 public Annotation[] getDeclaredAnnotations() {
Peter Levartc7759dc2013-09-19 16:14:13 +02003710 return AnnotationParser.toArray(annotationData().declaredAnnotations);
3711 }
3712
3713 // annotation data that might get invalidated when JVM TI RedefineClasses() is called
3714 private static class AnnotationData {
3715 final Map<Class<? extends Annotation>, Annotation> annotations;
3716 final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3717
3718 // Value of classRedefinedCount when we created this AnnotationData instance
3719 final int redefinedCount;
3720
3721 AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
3722 Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
3723 int redefinedCount) {
3724 this.annotations = annotations;
3725 this.declaredAnnotations = declaredAnnotations;
3726 this.redefinedCount = redefinedCount;
3727 }
J. Duke319a3b92007-12-01 00:00:00 +00003728 }
3729
3730 // Annotations cache
Peter Levartc7759dc2013-09-19 16:14:13 +02003731 @SuppressWarnings("UnusedDeclaration")
Martin Buchholza2f0fe32015-09-15 21:56:04 -07003732 private transient volatile AnnotationData annotationData;
Peter Levarte9127732013-01-13 19:57:06 -05003733
Peter Levartc7759dc2013-09-19 16:14:13 +02003734 private AnnotationData annotationData() {
3735 while (true) { // retry loop
3736 AnnotationData annotationData = this.annotationData;
3737 int classRedefinedCount = this.classRedefinedCount;
3738 if (annotationData != null &&
3739 annotationData.redefinedCount == classRedefinedCount) {
3740 return annotationData;
3741 }
3742 // null or stale annotationData -> optimistically create new instance
3743 AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
3744 // try to install it
3745 if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
3746 // successfully installed new AnnotationData
3747 return newAnnotationData;
3748 }
Peter Levarte9127732013-01-13 19:57:06 -05003749 }
3750 }
J. Duke319a3b92007-12-01 00:00:00 +00003751
Peter Levartc7759dc2013-09-19 16:14:13 +02003752 private AnnotationData createAnnotationData(int classRedefinedCount) {
3753 Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
3754 AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
J. Duke319a3b92007-12-01 00:00:00 +00003755 Class<?> superClass = getSuperclass();
Peter Levartc7759dc2013-09-19 16:14:13 +02003756 Map<Class<? extends Annotation>, Annotation> annotations = null;
3757 if (superClass != null) {
3758 Map<Class<? extends Annotation>, Annotation> superAnnotations =
3759 superClass.annotationData().annotations;
3760 for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
3761 Class<? extends Annotation> annotationClass = e.getKey();
3762 if (AnnotationType.getInstance(annotationClass).isInherited()) {
3763 if (annotations == null) { // lazy construction
3764 annotations = new LinkedHashMap<>((Math.max(
3765 declaredAnnotations.size(),
3766 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
3767 ) * 4 + 2) / 3
3768 );
3769 }
3770 annotations.put(annotationClass, e.getValue());
3771 }
3772 }
3773 }
3774 if (annotations == null) {
3775 // no inherited annotations -> share the Map with declaredAnnotations
J. Duke319a3b92007-12-01 00:00:00 +00003776 annotations = declaredAnnotations;
3777 } else {
Peter Levartc7759dc2013-09-19 16:14:13 +02003778 // at least one inherited annotation -> declared may override inherited
J. Duke319a3b92007-12-01 00:00:00 +00003779 annotations.putAll(declaredAnnotations);
3780 }
Peter Levartc7759dc2013-09-19 16:14:13 +02003781 return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
J. Duke319a3b92007-12-01 00:00:00 +00003782 }
3783
3784 // Annotation types cache their internal (AnnotationType) form
3785
Peter Levartb0d16762013-07-15 10:55:53 +02003786 @SuppressWarnings("UnusedDeclaration")
Martin Buchholza2f0fe32015-09-15 21:56:04 -07003787 private transient volatile AnnotationType annotationType;
J. Duke319a3b92007-12-01 00:00:00 +00003788
Peter Levartb0d16762013-07-15 10:55:53 +02003789 boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3790 return Atomic.casAnnotationType(this, oldType, newType);
J. Duke319a3b92007-12-01 00:00:00 +00003791 }
3792
3793 AnnotationType getAnnotationType() {
3794 return annotationType;
3795 }
John R Rosecec41c42012-01-18 17:34:32 -08003796
Andreas Lundblad5db9cc72013-10-24 18:52:13 +02003797 Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
3798 return annotationData().declaredAnnotations;
3799 }
3800
John R Rosecec41c42012-01-18 17:34:32 -08003801 /* Backing store of user-defined values pertaining to this class.
3802 * Maintained by the ClassValue class.
3803 */
3804 transient ClassValue.ClassValueMap classValueMap;
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003805
3806 /**
Joel Borggrén-Franck279576c2013-09-30 11:18:18 +02003807 * Returns an {@code AnnotatedType} object that represents the use of a
3808 * type to specify the superclass of the entity represented by this {@code
3809 * Class} object. (The <em>use</em> of type Foo to specify the superclass
3810 * in '... extends Foo' is distinct from the <em>declaration</em> of type
3811 * Foo.)
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003812 *
Joel Borggrén-Franck279576c2013-09-30 11:18:18 +02003813 * <p> If this {@code Class} object represents a type whose declaration
3814 * does not explicitly indicate an annotated superclass, then the return
3815 * value is an {@code AnnotatedType} object representing an element with no
3816 * annotations.
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003817 *
Joel Borggrén-Franck279576c2013-09-30 11:18:18 +02003818 * <p> If this {@code Class} represents either the {@code Object} class, an
3819 * interface type, an array type, a primitive type, or void, the return
3820 * value is {@code null}.
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003821 *
Joe Darcye751cc72013-06-24 23:40:31 -07003822 * @return an object representing the superclass
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003823 * @since 1.8
3824 */
3825 public AnnotatedType getAnnotatedSuperclass() {
Joel Borggrén-Franckd4b28472013-08-26 13:38:14 +02003826 if (this == Object.class ||
3827 isInterface() ||
3828 isArray() ||
3829 isPrimitive() ||
3830 this == Void.TYPE) {
3831 return null;
3832 }
3833
3834 return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3835 }
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003836
3837 /**
Joel Borggrén-Franck279576c2013-09-30 11:18:18 +02003838 * Returns an array of {@code AnnotatedType} objects that represent the use
3839 * of types to specify superinterfaces of the entity represented by this
3840 * {@code Class} object. (The <em>use</em> of type Foo to specify a
3841 * superinterface in '... implements Foo' is distinct from the
3842 * <em>declaration</em> of type Foo.)
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003843 *
Joel Borggrén-Franck279576c2013-09-30 11:18:18 +02003844 * <p> If this {@code Class} object represents a class, the return value is
3845 * an array containing objects representing the uses of interface types to
3846 * specify interfaces implemented by the class. The order of the objects in
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003847 * the array corresponds to the order of the interface types used in the
Joel Borggrén-Franck279576c2013-09-30 11:18:18 +02003848 * 'implements' clause of the declaration of this {@code Class} object.
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003849 *
Joel Borggrén-Franck279576c2013-09-30 11:18:18 +02003850 * <p> If this {@code Class} object represents an interface, the return
3851 * value is an array containing objects representing the uses of interface
3852 * types to specify interfaces directly extended by the interface. The
3853 * order of the objects in the array corresponds to the order of the
3854 * interface types used in the 'extends' clause of the declaration of this
3855 * {@code Class} object.
3856 *
3857 * <p> If this {@code Class} object represents a class or interface whose
3858 * declaration does not explicitly indicate any annotated superinterfaces,
3859 * the return value is an array of length 0.
3860 *
3861 * <p> If this {@code Class} object represents either the {@code Object}
3862 * class, an array type, a primitive type, or void, the return value is an
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003863 * array of length 0.
3864 *
Joe Darcye751cc72013-06-24 23:40:31 -07003865 * @return an array representing the superinterfaces
Joel Borggrén-Franckb29b4792013-01-29 10:32:49 +01003866 * @since 1.8
3867 */
3868 public AnnotatedType[] getAnnotatedInterfaces() {
3869 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3870 }
J. Duke319a3b92007-12-01 00:00:00 +00003871}