~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to external/ikvm/openjdk/java/lang/Class.java

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

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