declare module 'java.lang.constant' { import { Optional, List, Map } from 'java.util'; import { Lookup } from 'java.lang.invoke.MethodHandles'; import { CallSite } from 'java.lang.invoke'; import { Function } from 'java.util.function'; import { Kind } from 'java.lang.constant.DirectMethodHandleDesc'; import { OfField, OfMethod } from 'java.lang.invoke.TypeDescriptor'; /** * A nominal descriptor for an * `invokedynamic` call site. * * Concrete subtypes of {@linkplain DynamicCallSiteDesc} should be immutable * and their behavior should not rely on object identity. * * @since 12 */ export class DynamicCallSiteDesc { /** * Creates a nominal descriptor for an `invokedynamic` call site. * * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the * bootstrap method for the `invokedynamic` * @param invocationName The unqualified name that would appear in the `NameAndType` * operand of the `invokedynamic` * @param invocationType a {@link MethodTypeDesc} describing the invocation * type that would appear in the `NameAndType` * operand of the `invokedynamic` * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments * to the bootstrap, that would appear in the * `BootstrapMethods` attribute * @return the nominal descriptor * @throws NullPointerException if any parameter is null * @throws IllegalArgumentException if the invocation name has the incorrect * format * @jvms 4.2.2 Unqualified Names */ static of(bootstrapMethod: DirectMethodHandleDesc, invocationName: string, invocationType: MethodTypeDesc, ...bootstrapArgs: ConstantDesc[]): DynamicCallSiteDesc; /** * Creates a nominal descriptor for an `invokedynamic` call site whose * bootstrap method has no static arguments. * * @param bootstrapMethod The bootstrap method for the `invokedynamic` * @param invocationName The invocationName that would appear in the * `NameAndType` operand of the `invokedynamic` * @param invocationType The invocation invocationType that would appear * in the `NameAndType` operand of the `invokedynamic` * @return the nominal descriptor * @throws NullPointerException if any parameter is null * @throws IllegalArgumentException if the invocation name has the incorrect * format */ static of(bootstrapMethod: DirectMethodHandleDesc, invocationName: string, invocationType: MethodTypeDesc): DynamicCallSiteDesc; /** * Creates a nominal descriptor for an `invokedynamic` call site whose * bootstrap method has no static arguments and for which the name parameter * is {@link ConstantDescs#DEFAULT_NAME}. * * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the * bootstrap method for the `invokedynamic` * @param invocationType a {@link MethodTypeDesc} describing the invocation * type that would appear in the `NameAndType` * operand of the `invokedynamic` * @return the nominal descriptor * @throws NullPointerException if any parameter is null */ static of(bootstrapMethod: DirectMethodHandleDesc, invocationType: MethodTypeDesc): DynamicCallSiteDesc; /** * Returns a nominal descriptor for an `invokedynamic` call site whose * bootstrap method, name, and invocation type are the same as this one, but * with the specified bootstrap arguments. * * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments * to the bootstrap, that would appear in the * `BootstrapMethods` attribute * @return the nominal descriptor * @throws NullPointerException if any parameter is null */ withArgs(...bootstrapArgs: ConstantDesc[]): DynamicCallSiteDesc; /** * Returns a nominal descriptor for an `invokedynamic` call site whose * bootstrap and bootstrap arguments are the same as this one, but with the * specified invocationName and invocation invocationType * * @param invocationName The unqualified name that would appear in the `NameAndType` * operand of the `invokedynamic` * @param invocationType a {@link MethodTypeDesc} describing the invocation * type that would appear in the `NameAndType` * operand of the `invokedynamic` * @return the nominal descriptor * @throws NullPointerException if any parameter is null * @throws IllegalArgumentException if the invocation name has the incorrect * format * @jvms 4.2.2 Unqualified Names */ withNameAndType(invocationName: string, invocationType: MethodTypeDesc): DynamicCallSiteDesc; /** * Returns the invocation name that would appear in the `NameAndType` * operand of the `invokedynamic`. * * @return the invocation name */ invocationName(): string; /** * Returns a {@link MethodTypeDesc} describing the invocation type that * would appear in the `NameAndType` operand of the `invokedynamic`. * * @return the invocation type */ invocationType(): MethodTypeDesc; /** * Returns a {@link MethodHandleDesc} describing the bootstrap method for * the `invokedynamic`. * * @return the bootstrap method for the `invokedynamic` */ bootstrapMethod(): MethodHandleDesc; /** * Returns {@link ConstantDesc}s describing the bootstrap arguments for the * `invokedynamic`. The returned array is always non-null. A zero * length array is returned if this {@linkplain DynamicCallSiteDesc} has no * bootstrap arguments. * * @return the bootstrap arguments for the `invokedynamic` */ bootstrapArgs(): ConstantDesc[]; /** * Reflectively invokes the bootstrap method with the specified arguments, * and return the resulting {@link CallSite} * * @param lookup The {@link MethodHandles.Lookup} used to resolve class names * @return the {@link CallSite} * @throws Throwable if any exception is thrown by the bootstrap method */ resolveCallSiteDesc(lookup: Lookup): CallSite; /** * Compares the specified object with this descriptor for equality. Returns * `true` if and only if the specified object is also a * {@linkplain DynamicCallSiteDesc}, and both descriptors have equal * bootstrap methods, bootstrap argument lists, invocation name, and * invocation type. * * @param o the `DynamicCallSiteDesc` to compare to this * `DynamicCallSiteDesc` * @return `true` if the specified `DynamicCallSiteDesc` * is equal to this `DynamicCallSiteDesc`. */ equals(o: any): boolean; hashCode(): number; /** * Returns a compact textual description of this call site description, * including the bootstrap method, the invocation name and type, and * the static bootstrap arguments. * * @return A compact textual description of this call site descriptor */ toString(): string; } /** * A nominal descriptor for a * {@linkplain MethodType} constant. * * @apiNote In the future, if the Java language permits, {@linkplain MethodTypeDesc} * may become a `sealed` interface, which would prohibit subclassing except * by explicitly permitted types. Non-platform classes should not implement * {@linkplain MethodTypeDesc} directly. * * @since 12 */ export class MethodTypeDesc extends ConstantDesc { /** * Creates a {@linkplain MethodTypeDesc} given a method descriptor string. * * @param descriptor a method descriptor string * @return a {@linkplain MethodTypeDesc} describing the desired method type * @throws NullPointerException if the argument is `null` * @throws IllegalArgumentException if the descriptor string is not a valid * method descriptor * @jvms 4.3.3 Method Descriptors */ static ofDescriptor(descriptor: string): MethodTypeDesc; /** * Returns a {@linkplain MethodTypeDesc} given the return type and parameter * types. * * @param returnDesc a {@linkplain ClassDesc} describing the return type * @param paramDescs {@linkplain ClassDesc}s describing the argument types * @return a {@linkplain MethodTypeDesc} describing the desired method type * @throws NullPointerException if any argument or its contents are `null` * @throws IllegalArgumentException if any element of `paramDescs` is a * {@link ClassDesc} for `void` */ static of(returnDesc: ClassDesc, ...paramDescs: ClassDesc[]): MethodTypeDesc; /** * Gets the return type of the method type described by this {@linkplain MethodTypeDesc}. * * @return a {@link ClassDesc} describing the return type of the method type */ returnType(): ClassDesc; /** * Returns the number of parameters of the method type described by * this {@linkplain MethodTypeDesc}. * @return the number of parameters */ parameterCount(): number; /** * Returns the parameter type of the `index`'th parameter of the method type * described by this {@linkplain MethodTypeDesc}. * * @param index the index of the parameter to retrieve * @return a {@link ClassDesc} describing the desired parameter type * @throws IndexOutOfBoundsException if the index is outside the half-open * range {[0, parameterCount())} */ parameterType(index: number): ClassDesc; /** * Returns the parameter types as an immutable {@link List}. * * @return a {@link List} of {@link ClassDesc} describing the parameter types */ parameterList(): ClassDesc[]; /** * Returns the parameter types as an array. * * @return an array of {@link ClassDesc} describing the parameter types */ parameterArray(): ClassDesc[]; /** * Returns a {@linkplain MethodTypeDesc} that is identical to * this one, except with the specified return type. * * @param returnType a {@link ClassDesc} describing the new return type * @return a {@linkplain MethodTypeDesc} describing the desired method type * @throws NullPointerException if the argument is `null` */ changeReturnType(returnType: ClassDesc): MethodTypeDesc; /** * Returns a {@linkplain MethodTypeDesc} that is identical to this one, * except that a single parameter type has been changed to the specified type. * * @param index the index of the parameter to change * @param paramType a {@link ClassDesc} describing the new parameter type * @return a {@linkplain MethodTypeDesc} describing the desired method type * @throws NullPointerException if any argument is `null` * @throws IndexOutOfBoundsException if the index is outside the half-open * range {[0, parameterCount)} */ changeParameterType(index: number, paramType: ClassDesc): MethodTypeDesc; /** * Returns a {@linkplain MethodTypeDesc} that is identical to this one, * except that a range of parameter types have been removed. * * @param start the index of the first parameter to remove * @param end the index after the last parameter to remove * @return a {@linkplain MethodTypeDesc} describing the desired method type * @throws IndexOutOfBoundsException if `start` is outside the half-open * range `[0, parameterCount)`, or `end` is outside the closed range * `[0, parameterCount]`, or if `start > end` */ dropParameterTypes(start: number, end: number): MethodTypeDesc; /** * Returns a {@linkplain MethodTypeDesc} that is identical to this one, * except that a range of additional parameter types have been inserted. * * @param pos the index at which to insert the first inserted parameter * @param paramTypes {@link ClassDesc}s describing the new parameter types * to insert * @return a {@linkplain MethodTypeDesc} describing the desired method type * @throws NullPointerException if any argument or its contents are `null` * @throws IndexOutOfBoundsException if `pos` is outside the closed * range {[0, parameterCount]} * @throws IllegalArgumentException if any element of `paramTypes` * is a {@link ClassDesc} for `void` */ insertParameterTypes(pos: number, ...paramTypes: ClassDesc[]): MethodTypeDesc; /** * Returns the method type descriptor string. * * @return the method type descriptor string * @jvms 4.3.3 Method Descriptors */ descriptorString(): string; /** * Returns a human-readable descriptor for this method type, using the * canonical names for parameter and return types. * * @return the human-readable descriptor for this method type */ displayDescriptor(): string; /** * Compares the specified object with this descriptor for equality. Returns * `true` if and only if the specified object is also a * {@linkplain MethodTypeDesc} both have the same arity, their return types * are equal, and each pair of corresponding parameter types are equal. * * @param o the other object * @return whether this descriptor is equal to the other object */ equals(o: any): boolean; } export interface MethodTypeDesc extends ConstantDesc, OfMethod {} /** * Predefined values of nominal descriptor * for common constants, including descriptors for primitive class types and * other common platform types, and descriptors for method handles for standard * bootstrap methods. * * @see ConstantDesc * * @since 12 */ export class ConstantDescs { /** Invocation name to use when no name is needed, such as the name of a * constructor, or the invocation name of a dynamic constant or dynamic * callsite when the bootstrap is known to ignore the invocation name. */ static readonly DEFAULT_NAME: string; /** {@link ClassDesc} representing {@link Object} */ static readonly CD_Object: ClassDesc; /** {@link ClassDesc} representing {@link String} */ static readonly CD_String: ClassDesc; /** {@link ClassDesc} representing {@link Class} */ static readonly CD_Class: ClassDesc; /** {@link ClassDesc} representing {@link Number} */ static readonly CD_Number: ClassDesc; /** {@link ClassDesc} representing {@link Integer} */ static readonly CD_Integer: ClassDesc; /** {@link ClassDesc} representing {@link Long} */ static readonly CD_Long: ClassDesc; /** {@link ClassDesc} representing {@link Float} */ static readonly CD_Float: ClassDesc; /** {@link ClassDesc} representing {@link Double} */ static readonly CD_Double: ClassDesc; /** {@link ClassDesc} representing {@link Short} */ static readonly CD_Short: ClassDesc; /** {@link ClassDesc} representing {@link Byte} */ static readonly CD_Byte: ClassDesc; /** {@link ClassDesc} representing {@link Character} */ static readonly CD_Character: ClassDesc; /** {@link ClassDesc} representing {@link Boolean} */ static readonly CD_Boolean: ClassDesc; /** {@link ClassDesc} representing {@link Void} */ static readonly CD_Void: ClassDesc; /** {@link ClassDesc} representing {@link Throwable} */ static readonly CD_Throwable: ClassDesc; /** {@link ClassDesc} representing {@link Exception} */ static readonly CD_Exception: ClassDesc; /** {@link ClassDesc} representing {@link Enum} */ static readonly CD_Enum: ClassDesc; /** {@link ClassDesc} representing {@link VarHandle} */ static readonly CD_VarHandle: ClassDesc; /** {@link ClassDesc} representing {@link MethodHandles} */ static readonly CD_MethodHandles: ClassDesc; /** {@link ClassDesc} representing {@link MethodHandles.Lookup} */ static readonly CD_MethodHandles_Lookup: ClassDesc; /** {@link ClassDesc} representing {@link MethodHandle} */ static readonly CD_MethodHandle: ClassDesc; /** {@link ClassDesc} representing {@link MethodType} */ static readonly CD_MethodType: ClassDesc; /** {@link ClassDesc} representing {@link CallSite} */ static readonly CD_CallSite: ClassDesc; /** {@link ClassDesc} representing {@link Collection} */ static readonly CD_Collection: ClassDesc; /** {@link ClassDesc} representing {@link List} */ static readonly CD_List: ClassDesc; /** {@link ClassDesc} representing {@link Set} */ static readonly CD_Set: ClassDesc; /** {@link ClassDesc} representing {@link Map} */ static readonly CD_Map: ClassDesc; /** {@link ClassDesc} representing {@link ConstantDesc} */ static readonly CD_ConstantDesc: ClassDesc; /** {@link ClassDesc} representing {@link ClassDesc} */ static readonly CD_ClassDesc: ClassDesc; /** {@link ClassDesc} representing {@link EnumDesc} */ static readonly CD_EnumDesc: ClassDesc; /** {@link ClassDesc} representing {@link MethodTypeDesc} */ static readonly CD_MethodTypeDesc: ClassDesc; /** {@link ClassDesc} representing {@link MethodHandleDesc} */ static readonly CD_MethodHandleDesc: ClassDesc; /** {@link ClassDesc} representing {@link DirectMethodHandleDesc} */ static readonly CD_DirectMethodHandleDesc: ClassDesc; /** {@link ClassDesc} representing {@link VarHandleDesc} */ static readonly CD_VarHandleDesc: ClassDesc; /** {@link ClassDesc} representing {@link DirectMethodHandleDesc.Kind} */ static readonly CD_MethodHandleDesc_Kind: ClassDesc; /** {@link ClassDesc} representing {@link DynamicConstantDesc} */ static readonly CD_DynamicConstantDesc: ClassDesc; /** {@link ClassDesc} representing {@link DynamicCallSiteDesc} */ static readonly CD_DynamicCallSiteDesc: ClassDesc; /** {@link ClassDesc} representing {@link ConstantBootstraps} */ static readonly CD_ConstantBootstraps: ClassDesc; /** {@link MethodHandleDesc} representing {@link ConstantBootstraps#primitiveClass(Lookup, String, Class) ConstantBootstraps.primitiveClass} */ static readonly BSM_PRIMITIVE_CLASS: DirectMethodHandleDesc; /** {@link MethodHandleDesc} representing {@link ConstantBootstraps#enumConstant(Lookup, String, Class) ConstantBootstraps.enumConstant} */ static readonly BSM_ENUM_CONSTANT: DirectMethodHandleDesc; /** * {@link MethodHandleDesc} representing {@link ConstantBootstraps#getStaticFinal(Lookup, String, Class, Class) ConstantBootstraps.getStaticFinal} * @since 15 */ static readonly BSM_GET_STATIC_FINAL: DirectMethodHandleDesc; /** {@link MethodHandleDesc} representing {@link ConstantBootstraps#nullConstant(Lookup, String, Class) ConstantBootstraps.nullConstant} */ static readonly BSM_NULL_CONSTANT: DirectMethodHandleDesc; /** {@link MethodHandleDesc} representing {@link ConstantBootstraps#fieldVarHandle(Lookup, String, Class, Class, Class) ConstantBootstraps.fieldVarHandle} */ static readonly BSM_VARHANDLE_FIELD: DirectMethodHandleDesc; /** {@link MethodHandleDesc} representing {@link ConstantBootstraps#staticFieldVarHandle(Lookup, String, Class, Class, Class) ConstantBootstraps.staticVarHandle} */ static readonly BSM_VARHANDLE_STATIC_FIELD: DirectMethodHandleDesc; /** {@link MethodHandleDesc} representing {@link ConstantBootstraps#arrayVarHandle(Lookup, String, Class, Class) ConstantBootstraps.arrayVarHandle} */ static readonly BSM_VARHANDLE_ARRAY: DirectMethodHandleDesc; /** {@link MethodHandleDesc} representing {@link ConstantBootstraps#invoke(Lookup, String, Class, MethodHandle, Object...) ConstantBootstraps.invoke} */ static readonly BSM_INVOKE: DirectMethodHandleDesc; /** * {@link MethodHandleDesc} representing {@link ConstantBootstraps#explicitCast(Lookup, String, Class, Object)} ConstantBootstraps.explicitCast} * @since 15 */ static readonly BSM_EXPLICIT_CAST: DirectMethodHandleDesc; /** {@link ClassDesc} representing the primitive type `int` */ static readonly CD_int: ClassDesc; /** {@link ClassDesc} representing the primitive type `long` */ static readonly CD_long: ClassDesc; /** {@link ClassDesc} representing the primitive type `float` */ static readonly CD_float: ClassDesc; /** {@link ClassDesc} representing the primitive type `double` */ static readonly CD_double: ClassDesc; /** {@link ClassDesc} representing the primitive type `short` */ static readonly CD_short: ClassDesc; /** {@link ClassDesc} representing the primitive type `byte` */ static readonly CD_byte: ClassDesc; /** {@link ClassDesc} representing the primitive type `char` */ static readonly CD_char: ClassDesc; /** {@link ClassDesc} representing the primitive type `boolean` */ static readonly CD_boolean: ClassDesc; /** {@link ClassDesc} representing the primitive type `void` */ static readonly CD_void: ClassDesc; /** Nominal descriptor representing the constant `null` */ static readonly NULL: ConstantDesc; /** * Nominal descriptor representing the constant {@linkplain Boolean#TRUE} * @since 15 */ static readonly TRUE: DynamicConstantDesc; /** * Nominal descriptor representing the constant {@linkplain Boolean#FALSE} * @since 15 */ static readonly FALSE: DynamicConstantDesc; /** * Returns a {@link MethodHandleDesc} corresponding to a bootstrap method for * an `invokedynamic` callsite, which is a static method whose leading * parameter types are `Lookup`, `String`, and `MethodType`. * * @param owner the class declaring the method * @param name the unqualified name of the method * @param returnType the return type of the method * @param paramTypes the types of the static bootstrap arguments, if any * @return the {@link MethodHandleDesc} * @throws NullPointerException if any of the arguments are null * @jvms 4.2.2 Unqualified Names */ static ofCallsiteBootstrap(owner: ClassDesc, name: string, returnType: ClassDesc, ...paramTypes: ClassDesc[]): DirectMethodHandleDesc; /** * Returns a {@link MethodHandleDesc} corresponding to a bootstrap method for a * dynamic constant, which is a static method whose leading arguments are * `Lookup`, `String`, and `Class`. * * @param owner the class declaring the method * @param name the unqualified name of the method * @param returnType the return type of the method * @param paramTypes the types of the static bootstrap arguments, if any * @return the {@link MethodHandleDesc} * @throws NullPointerException if any of the arguments are null * @jvms 4.2.2 Unqualified Names */ static ofConstantBootstrap(owner: ClassDesc, name: string, returnType: ClassDesc, ...paramTypes: ClassDesc[]): DirectMethodHandleDesc; } /** * A nominal descriptor for a * {@link Class} constant. * * For common system types, including all the primitive types, there are * predefined {@linkplain ClassDesc} constants in {@link ConstantDescs}. * (The `java.lang.constant` APIs consider `void` to be a primitive type.) * To create a {@linkplain ClassDesc} for a class or interface type, use {@link #of} or * {@link #ofDescriptor(String)}; to create a {@linkplain ClassDesc} for an array * type, use {@link #ofDescriptor(String)}, or first obtain a * {@linkplain ClassDesc} for the component type and then call the {@link #arrayType()} * or {@link #arrayType(int)} methods. * * @apiNote In the future, if the Java language permits, {@linkplain ClassDesc} * may become a `sealed` interface, which would prohibit subclassing except * by explicitly permitted types. Non-platform classes should not implement * {@linkplain ClassDesc} directly. * * @see ConstantDescs * * @since 12 */ export class ClassDesc extends ConstantDesc { /** * Returns a {@linkplain ClassDesc} for a class or interface type, * given the name of the class or interface, such as `"java.lang.String"`. * (To create a descriptor for an array type, either use {@link #ofDescriptor(String)} * or {@link #arrayType()}; to create a descriptor for a primitive type, use * {@link #ofDescriptor(String)} or use the predefined constants in * {@link ConstantDescs}). * * @param name the fully qualified (dot-separated) binary class name * @return a {@linkplain ClassDesc} describing the desired class * @throws NullPointerException if the argument is `null` * @throws IllegalArgumentException if the name string is not in the * correct format */ static of(name: string): ClassDesc; /** * Returns a {@linkplain ClassDesc} for a class or interface type, * given a package name and the unqualified (simple) name for the * class or interface. * * @param packageName the package name (dot-separated); if the package * name is the empty string, the class is considered to * be in the unnamed package * @param className the unqualified (simple) class name * @return a {@linkplain ClassDesc} describing the desired class * @throws NullPointerException if any argument is `null` * @throws IllegalArgumentException if the package name or class name are * not in the correct format */ static of(packageName: string, className: string): ClassDesc; /** * Returns a {@linkplain ClassDesc} given a descriptor string for a class, * interface, array, or primitive type. * * @apiNote * * A field type descriptor string for a non-array type is either * a one-letter code corresponding to a primitive type * (`"J", "I", "C", "S", "B", "D", "F", "Z", "V"`), or the letter `"L"`, followed * by the fully qualified binary name of a class, followed by `";"`. * A field type descriptor for an array type is the character `"["` * followed by the field descriptor for the component type. Examples of * valid type descriptor strings include `"Ljava/lang/String;"`, `"I"`, * `"[I"`, `"V"`, `"[Ljava/lang/String;"`, etc. * See JVMS 4.3.2 ("Field Descriptors") for more detail. * * @param descriptor a field descriptor string * @return a {@linkplain ClassDesc} describing the desired class * @throws NullPointerException if the argument is `null` * @throws IllegalArgumentException if the name string is not in the * correct format * @jvms 4.3.2 Field Descriptors * @jvms 4.4.1 The CONSTANT_Class_info Structure */ static ofDescriptor(descriptor: string): ClassDesc; /** * Returns a {@linkplain ClassDesc} for an array type whose component type * is described by this {@linkplain ClassDesc}. * * @return a {@linkplain ClassDesc} describing the array type * @throws IllegalStateException if the resulting {@linkplain ClassDesc} would have an array rank of greater than 255 * @jvms 4.4.1 The CONSTANT_Class_info Structure */ arrayType(): ClassDesc; /** * Returns a {@linkplain ClassDesc} for an array type of the specified rank, * whose component type is described by this {@linkplain ClassDesc}. * * @param rank the rank of the array * @return a {@linkplain ClassDesc} describing the array type * @throws IllegalArgumentException if the rank is less than or equal to zero or if the rank of the resulting array type is * greater than 255 * @jvms 4.4.1 The CONSTANT_Class_info Structure */ arrayType(rank: number): ClassDesc; /** * Returns a {@linkplain ClassDesc} for a nested class of the class or * interface type described by this {@linkplain ClassDesc}. * * @apiNote * * Example: If descriptor `d` describes the class `java.util.Map`, a * descriptor for the class `java.util.Map.Entry` could be obtained * by `d.nested("Entry")`. * * @param nestedName the unqualified name of the nested class * @return a {@linkplain ClassDesc} describing the nested class * @throws NullPointerException if the argument is `null` * @throws IllegalStateException if this {@linkplain ClassDesc} does not * describe a class or interface type * @throws IllegalArgumentException if the nested class name is invalid */ nested(nestedName: string): ClassDesc; /** * Returns a {@linkplain ClassDesc} for a nested class of the class or * interface type described by this {@linkplain ClassDesc}. * * @param firstNestedName the unqualified name of the first level of nested class * @param moreNestedNames the unqualified name(s) of the remaining levels of * nested class * @return a {@linkplain ClassDesc} describing the nested class * @throws NullPointerException if any argument or its contents is `null` * @throws IllegalStateException if this {@linkplain ClassDesc} does not * describe a class or interface type * @throws IllegalArgumentException if the nested class name is invalid */ nested(firstNestedName: string, ...moreNestedNames: string[]): ClassDesc; /** * Returns whether this {@linkplain ClassDesc} describes an array type. * * @return whether this {@linkplain ClassDesc} describes an array type */ isArray(): boolean; /** * Returns whether this {@linkplain ClassDesc} describes a primitive type. * * @return whether this {@linkplain ClassDesc} describes a primitive type */ isPrimitive(): boolean; /** * Returns whether this {@linkplain ClassDesc} describes a class or interface type. * * @return whether this {@linkplain ClassDesc} describes a class or interface type */ isClassOrInterface(): boolean; /** * Returns the component type of this {@linkplain ClassDesc}, if it describes * an array type, or `null` otherwise. * * @return a {@linkplain ClassDesc} describing the component type, or `null` * if this descriptor does not describe an array type */ componentType(): ClassDesc; /** * Returns the package name of this {@linkplain ClassDesc}, if it describes * a class or interface type. * * @return the package name, or the empty string if the class is in the * default package, or this {@linkplain ClassDesc} does not describe a class or interface type */ packageName(): string; /** * Returns a human-readable name for the type described by this descriptor. * * @implSpec * The default implementation returns the simple name * (e.g., `int`) for primitive types, the unqualified class name * for class or interface types, or the display name of the component type * suffixed with the appropriate number of `[]` pairs for array types. * * @return the human-readable name */ displayName(): string; /** * Returns a field type descriptor string for this type * * @return the descriptor string * @jvms 4.3.2 Field Descriptors */ descriptorString(): string; /** * Compare the specified object with this descriptor for equality. Returns * `true` if and only if the specified object is also a * {@linkplain ClassDesc} and both describe the same type. * * @param o the other object * @return whether this descriptor is equal to the other object */ equals(o: any): boolean; } export interface ClassDesc extends ConstantDesc, OfField {} /** * A nominal descriptor for a direct * {@link MethodHandle}. A {@linkplain DirectMethodHandleDesc} corresponds to * a `Constant_MethodHandle_info` entry in the constant pool of a classfile. * * @apiNote In the future, if the Java language permits, {@linkplain DirectMethodHandleDesc} * may become a `sealed` interface, which would prohibit subclassing except * by explicitly permitted types. Non-platform classes should not implement * {@linkplain DirectMethodHandleDesc} directly. * * @since 12 */ export class DirectMethodHandleDesc extends MethodHandleDesc { /** * Returns the `kind` of the method handle described by this nominal * descriptor. * * @return the {@link Kind} */ kind(): Kind; /** * Returns the `refKind` of the method handle described by this nominal * reference, as defined by {@link MethodHandleInfo}. * * @return the reference kind */ refKind(): number; /** * Indicates if the method is declared by an interface * * @return true if the method is declared by an interface */ isOwnerInterface(): boolean; /** * Returns a {@link ClassDesc} describing the class declaring the * method or field described by this nominal descriptor. * * @return the class declaring the method or field */ owner(): ClassDesc; /** * Returns the name of the method or field described by this nominal descriptor. * For constructors, returns the reserved name `""`. * * @return the name of the method or field */ methodName(): string; /** * Returns the lookup descriptor of the method handle described by this descriptor, * after adjusting for the invocation mode. This will correspond to either * a method type descriptor string (for methods and constructors), or a field * descriptor string (for field access method handles). The lookup descriptor * string is in the same format as accepted by {@link MethodHandleDesc#of(Kind, ClassDesc, String, String)}. * * @return the lookup descriptor string */ lookupDescriptor(): string; } /** * A nominal descriptor for a * dynamic constant (one described in the constant pool with * `Constant_Dynamic_info`.) * * Concrete subtypes of {@linkplain DynamicConstantDesc} should be immutable * and their behavior should not rely on object identity. * * @param the type of the dynamic constant * * @since 12 */ export class DynamicConstantDesc extends ConstantDesc { /** * Returns a nominal descriptor for a dynamic constant, transforming it into * a more specific type if the constant bootstrap is a well-known one and a * more specific nominal descriptor type (e.g., ClassDesc) is available. * * Classes whose {@link Constable#describeConstable()} method produce * a {@linkplain DynamicConstantDesc} with a well-known bootstrap including * {@link Class} (for instances describing primitive types), {@link Enum}, * and {@link VarHandle}. * * Bytecode-reading APIs that process the constant pool and wish to expose * entries as {@link ConstantDesc} to their callers should generally use this * method in preference to {@link #ofNamed(DirectMethodHandleDesc, String, ClassDesc, ConstantDesc...)} * because this may result in a more specific type that can be provided to * callers. * * @param the type of the dynamic constant * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the * bootstrap method for the constant * @param constantName The unqualified name that would appear in the `NameAndType` * operand of the `LDC` for this constant * @param constantType a {@link ClassDesc} describing the type * that would appear in the `NameAndType` operand * of the `LDC` for this constant * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments * to the bootstrap, that would appear in the * `BootstrapMethods` attribute * @return the nominal descriptor * @throws NullPointerException if any argument is null * @throws IllegalArgumentException if the `name` has the incorrect * format * @jvms 4.2.2 Unqualified Names */ static ofCanonical(bootstrapMethod: DirectMethodHandleDesc, constantName: string, constantType: ClassDesc, bootstrapArgs: ConstantDesc[]): ConstantDesc; static ofNamed(bootstrapMethod: DirectMethodHandleDesc, constantName: string, constantType: ClassDesc, ...bootstrapArgs: ConstantDesc[]): DynamicConstantDesc; /** * Returns a nominal descriptor for a dynamic constant whose name parameter * is {@link ConstantDescs#DEFAULT_NAME}, and whose type parameter is always * the same as the bootstrap method return type. * * @param the type of the dynamic constant * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the * bootstrap method for the constant * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments * to the bootstrap, that would appear in the * `BootstrapMethods` attribute * @return the nominal descriptor * @throws NullPointerException if any argument is null * @jvms 4.2.2 Unqualified Names */ static of(bootstrapMethod: DirectMethodHandleDesc, ...bootstrapArgs: ConstantDesc[]): DynamicConstantDesc; /** * Returns a nominal descriptor for a dynamic constant whose bootstrap has * no static arguments, whose name parameter is {@link ConstantDescs#DEFAULT_NAME}, * and whose type parameter is always the same as the bootstrap method return type. * * @param the type of the dynamic constant * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the * bootstrap method for the constant * @return the nominal descriptor * @throws NullPointerException if any argument is null */ static of(bootstrapMethod: DirectMethodHandleDesc): DynamicConstantDesc; /** * Returns the name that would appear in the `NameAndType` operand * of the `LDC` for this constant. * * @return the constant name */ constantName(): string; /** * Returns a {@link ClassDesc} describing the type that would appear in the * `NameAndType` operand of the `LDC` for this constant. * * @return the constant type */ constantType(): ClassDesc; /** * Returns a {@link MethodHandleDesc} describing the bootstrap method for * this constant. * * @return the bootstrap method */ bootstrapMethod(): DirectMethodHandleDesc; /** * Returns the bootstrap arguments for this constant. * * @return the bootstrap arguments */ bootstrapArgs(): ConstantDesc[]; /** * Returns the bootstrap arguments for this constant as an immutable {@link List}. * * @return a {@link List} of the bootstrap arguments */ bootstrapArgsList(): ConstantDesc[]; resolveConstantDesc(lookup: Lookup): T; /** * Compares the specified object with this descriptor for equality. Returns * `true` if and only if the specified object is also a * {@linkplain DynamicConstantDesc}, and both descriptors have equal * bootstrap methods, bootstrap argument lists, constant name, and * constant type. * * @param o the `DynamicConstantDesc` to compare to this * `DynamicConstantDesc` * @return `true` if the specified `DynamicConstantDesc` * is equal to this `DynamicConstantDesc`. * */ equals(o: any): boolean; hashCode(): number; /** * Returns a compact textual description of this constant description, * including the bootstrap method, the constant name and type, and * the static bootstrap arguments. * * @return A compact textual description of this call site descriptor */ toString(): string; } /** * A nominal descriptor for a * {@link MethodHandle} constant. * * @apiNote In the future, if the Java language permits, {@linkplain MethodHandleDesc} * may become a `sealed` interface, which would prohibit subclassing except * by explicitly permitted types. Non-platform classes should not implement * {@linkplain MethodHandleDesc} directly. * * @since 12 */ export class MethodHandleDesc extends ConstantDesc { /** * Creates a {@linkplain MethodHandleDesc} corresponding to an invocation of a * declared method, invocation of a constructor, or access to a field. * * The lookup descriptor string has the same format as for the various * variants of `CONSTANT_MethodHandle_info` and for the lookup * methods on {@link MethodHandles.Lookup}. For a method or constructor * invocation, it is interpreted as a method type descriptor; for field * access, it is interpreted as a field descriptor. If `kind` is * `CONSTRUCTOR`, the `name` parameter is ignored and the return * type of the lookup descriptor must be `void`. If `kind` * corresponds to a virtual method invocation, the lookup type includes the * method parameters but not the receiver type. * * @param kind The kind of method handle to be described * @param owner a {@link ClassDesc} describing the class containing the * method, constructor, or field * @param name the unqualified name of the method or field (ignored if * `kind` is `CONSTRUCTOR`) * @param lookupDescriptor a method descriptor string the lookup type, * if the request is for a method invocation, or * describing the invocation type, if the request is * for a field or constructor * @return the {@linkplain MethodHandleDesc} * @throws NullPointerException if any of the non-ignored arguments are null * @throws IllegalArgumentException if the descriptor string is not a valid * method or field descriptor * @jvms 4.4.8 The CONSTANT_MethodHandle_info Structure * @jvms 4.2.2 Unqualified Names * @jvms 4.3.2 Field Descriptors * @jvms 4.3.3 Method Descriptors */ static of(kind: Kind, owner: ClassDesc, name: string, lookupDescriptor: string): DirectMethodHandleDesc; /** * Creates a {@linkplain MethodHandleDesc} corresponding to an invocation of a * declared method or constructor. * * The lookup descriptor string has the same format as for the lookup * methods on {@link MethodHandles.Lookup}. If `kind` is * `CONSTRUCTOR`, the name is ignored and the return type of the lookup * type must be `void`. If `kind` corresponds to a virtual method * invocation, the lookup type includes the method parameters but not the * receiver type. * * @param kind The kind of method handle to be described; must be one of * {@code SPECIAL, VIRTUAL, STATIC, INTERFACE_SPECIAL, * INTERFACE_VIRTUAL, INTERFACE_STATIC, CONSTRUCTOR} * @param owner a {@link ClassDesc} describing the class containing the * method or constructor * @param name the unqualified name of the method (ignored if `kind` * is `CONSTRUCTOR`) * @param lookupMethodType a {@link MethodTypeDesc} describing the lookup type * @return the {@linkplain MethodHandleDesc} * @throws NullPointerException if any non-ignored arguments are null * @throws IllegalArgumentException if the `name` has the incorrect * format, or the kind is invalid * @jvms 4.2.2 Unqualified Names */ static ofMethod(kind: Kind, owner: ClassDesc, name: string, lookupMethodType: MethodTypeDesc): DirectMethodHandleDesc; /** * Creates a {@linkplain MethodHandleDesc} corresponding to a method handle * that accesses a field. * * @param kind the kind of the method handle to be described; must be one of `GETTER`, * `SETTER`, `STATIC_GETTER`, or `STATIC_SETTER` * @param owner a {@link ClassDesc} describing the class containing the field * @param fieldName the unqualified name of the field * @param fieldType a {@link ClassDesc} describing the type of the field * @return the {@linkplain MethodHandleDesc} * @throws NullPointerException if any of the arguments are null * @throws IllegalArgumentException if the `kind` is not one of the * valid values or if the field name is not valid * @jvms 4.2.2 Unqualified Names */ static ofField(kind: Kind, owner: ClassDesc, fieldName: string, fieldType: ClassDesc): DirectMethodHandleDesc; /** * Returns a {@linkplain MethodHandleDesc} corresponding to invocation of a constructor * * @param owner a {@link ClassDesc} describing the class containing the * constructor * @param paramTypes {@link ClassDesc}s describing the parameter types of * the constructor * @return the {@linkplain MethodHandleDesc} * @throws NullPointerException if any argument or its contents is `null` */ static ofConstructor(owner: ClassDesc, ...paramTypes: ClassDesc[]): DirectMethodHandleDesc; /** * Returns a {@linkplain MethodHandleDesc} that describes this method handle * adapted to a different type, as if by {@link MethodHandle#asType(MethodType)}. * * @param type a {@link MethodHandleDesc} describing the new method type * @return a {@linkplain MethodHandleDesc} for the adapted method handle * @throws NullPointerException if the argument is `null` */ asType(type: MethodTypeDesc): MethodHandleDesc; /** * Returns a {@link MethodTypeDesc} describing the invocation type of the * method handle described by this nominal descriptor. The invocation type * describes the full set of stack values that are consumed by the invocation * (including the receiver, if any). * * @return a {@linkplain MethodHandleDesc} describing the method handle type */ invocationType(): MethodTypeDesc; /** * Compares the specified object with this descriptor for equality. Returns * `true` if and only if the specified object is also a * {@linkplain MethodHandleDesc}, and both encode the same nominal description * of a method handle. * * @param o the other object * @return whether this descriptor is equal to the other object */ equals(o: any): boolean; } /** * Represents a type which is constable. A constable type is one whose * values are constants that can be represented in the constant pool of a Java * classfile as described in JVMS 4.4, and whose instances can describe themselves * nominally as a {@link ConstantDesc}. * * Some constable types have a native representation in the constant pool: * {@link String}, {@link Integer}, {@link Long}, {@link Float}, * {@link Double}, {@link Class}, {@link MethodType}, and {@link MethodHandle}. * The types {@link String}, {@link Integer}, {@link Long}, {@link Float}, * and {@link Double} serve as their own nominal descriptors; {@link Class}, * {@link MethodType}, and {@link MethodHandle} have corresponding nominal * descriptors {@link ClassDesc}, {@link MethodTypeDesc}, and {@link MethodHandleDesc}. * * Other reference types can be constable if their instances can describe * themselves in nominal form as a {@link ConstantDesc}. Examples in the Java SE * Platform API are types that support Java language features such as {@link Enum}, * and runtime support classes such as {@link VarHandle}. These are typically * described with a {@link DynamicConstantDesc}, which describes dynamically * generated constants (JVMS 4.4.10). * * The nominal form of an instance of a constable type is obtained via * {@link #describeConstable()}. A {@linkplain Constable} need * not be able to (or may choose not to) describe all its instances in the form of * a {@link ConstantDesc}; this method returns an {@link Optional} that can be * empty to indicate that a nominal descriptor could not be created for an instance. * (For example, {@link MethodHandle} will produce nominal descriptors for direct * method handles, but not necessarily those produced by method handle * combinators.) * @jvms 4.4 The Constant Pool * @jvms 4.4.10 The `CONSTANT_Dynamic_info` and `CONSTANT_InvokeDynamic_info` Structures * * @since 12 */ export class Constable { /** * Returns an {@link Optional} containing the nominal descriptor for this * instance, if one can be constructed, or an empty {@link Optional} * if one cannot be constructed. * * @return An {@link Optional} containing the resulting nominal descriptor, * or an empty {@link Optional} if one cannot be constructed. */ describeConstable(): Optional; } /** * A nominal descriptor for a loadable * constant value, as defined in JVMS 4.4. Such a descriptor can be resolved via * {@link ConstantDesc#resolveConstantDesc(MethodHandles.Lookup)} to yield the * constant value itself. * * Class names in a nominal descriptor, like class names in the constant pool * of a classfile, must be interpreted with respect to a particular class * loader, which is not part of the nominal descriptor. * * Static constants that are expressible natively in the constant pool ({@link String}, * {@link Integer}, {@link Long}, {@link Float}, and {@link Double}) implement * {@link ConstantDesc}, and serve as nominal descriptors for themselves. * Native linkable constants ({@link Class}, {@link MethodType}, and * {@link MethodHandle}) have counterpart {@linkplain ConstantDesc} types: * {@link ClassDesc}, {@link MethodTypeDesc}, and {@link MethodHandleDesc}. * Other constants are represented by subtypes of {@link DynamicConstantDesc}. * * APIs that perform generation or parsing of bytecode are encouraged to use * {@linkplain ConstantDesc} to describe the operand of an `ldc` instruction * (including dynamic constants), the static bootstrap arguments of * dynamic constants and `invokedynamic` instructions, and other * bytecodes or classfile structures that make use of the constant pool. * * Constants describing various common constants (such as {@link ClassDesc} * instances for platform types) can be found in {@link ConstantDescs}. * * Implementations of {@linkplain ConstantDesc} should be immutable * and their behavior should not rely on object identity. * * Non-platform classes should not implement {@linkplain ConstantDesc} directly. * Instead, they should extend {@link DynamicConstantDesc} (as {@link EnumDesc} * and {@link VarHandleDesc} do.) * * Nominal descriptors should be compared using the * {@link Object#equals(Object)} method. There is no guarantee that any * particular entity will always be represented by the same descriptor instance. * * @apiNote In the future, if the Java language permits, {@linkplain ConstantDesc} * may become a `sealed` interface, which would prohibit subclassing except by * explicitly permitted types. Clients can assume that the following * set of subtypes is exhaustive: {@link String}, {@link Integer}, * {@link Long}, {@link Float}, {@link Double}, {@link ClassDesc}, * {@link MethodTypeDesc}, {@link MethodHandleDesc}, and * {@link DynamicConstantDesc}; this list may be extended to reflect future * changes to the constant pool format as defined in JVMS 4.4. * * @see Constable * @see ConstantDescs * * @jvms 4.4 The Constant Pool * * @since 12 */ export class ConstantDesc { /** * Resolves this descriptor reflectively, emulating the resolution behavior * of JVMS 5.4.3 and the access control behavior of JVMS 5.4.4. The resolution * and access control context is provided by the {@link MethodHandles.Lookup} * parameter. No caching of the resulting value is performed. * * @param lookup The {@link MethodHandles.Lookup} to provide name resolution * and access control context * @return the resolved constant value * @throws ReflectiveOperationException if a class, method, or field * could not be reflectively resolved in the course of resolution * @throws LinkageError if a linkage error occurs * * @apiNote {@linkplain MethodTypeDesc} can represent method type descriptors * that are not representable by {@linkplain MethodType}, such as methods with * more than 255 parameter slots, so attempts to resolve these may result in errors. * * @jvms 5.4.3 Resolution * @jvms 5.4.4 Access Control */ resolveConstantDesc(lookup: Lookup): any; } } declare module 'java.lang.System' { import { ResourceBundle } from 'java.util'; import { Throwable, RuntimePermission, Module } from 'java.lang'; import { Level } from 'java.lang.System.Logger'; import { Supplier } from 'java.util.function'; /** * `System.Logger` instances log messages that will be * routed to the underlying logging framework the {@link System.LoggerFinder * LoggerFinder} uses. * * `System.Logger` instances are typically obtained from * the {@link java.lang.System System} class, by calling * {@link java.lang.System#getLogger(java.lang.String) System.getLogger(loggerName)} * or {@link java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle) * System.getLogger(loggerName, bundle)}. * * @see java.lang.System#getLogger(java.lang.String) * @see java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle) * @see java.lang.System.LoggerFinder * * @since 9 */ export class Logger { /** * Returns the name of this logger. * * @return the logger name. */ get name(): string; /** * Checks if a message of the given level would be logged by * this logger. * * @param level the log message level. * @return `true` if the given log message level is currently * being logged. * * @throws NullPointerException if `level` is `null`. */ isLoggable(level: Level): boolean; /** * Logs a message. * * @implSpec The default implementation for this method calls * `this.log(level, (ResourceBundle)null, msg, (Object[])null);` * * @param level the log message level. * @param msg the string message (or a key in the message catalog, if * this logger is a {@link * LoggerFinder#getLocalizedLogger(java.lang.String, * java.util.ResourceBundle, java.lang.Module) localized logger}); * can be `null`. * * @throws NullPointerException if `level` is `null`. */ log(level: Level, msg: string): void; /** * Logs a lazily supplied message. * * If the logger is currently enabled for the given log message level * then a message is logged that is the result produced by the * given supplier function. Otherwise, the supplier is not operated on. * * @implSpec When logging is enabled for the given level, the default * implementation for this method calls * `this.log(level, (ResourceBundle)null, msgSupplier.get(), (Object[])null);` * * @param level the log message level. * @param msgSupplier a supplier function that produces a message. * * @throws NullPointerException if `level` is `null`, * or `msgSupplier` is `null`. */ log(level: Level, msgSupplier: Supplier): void; /** * Logs a message produced from the given object. * * If the logger is currently enabled for the given log message level then * a message is logged that, by default, is the result produced from * calling toString on the given object. * Otherwise, the object is not operated on. * * @implSpec When logging is enabled for the given level, the default * implementation for this method calls * `this.log(level, (ResourceBundle)null, obj.toString(), (Object[])null);` * * @param level the log message level. * @param obj the object to log. * * @throws NullPointerException if `level` is `null`, or * `obj` is `null`. */ log(level: Level, obj: any): void; /** * Logs a message associated with a given throwable. * * @implSpec The default implementation for this method calls * `this.log(level, (ResourceBundle)null, msg, thrown);` * * @param level the log message level. * @param msg the string message (or a key in the message catalog, if * this logger is a {@link * LoggerFinder#getLocalizedLogger(java.lang.String, * java.util.ResourceBundle, java.lang.Module) localized logger}); * can be `null`. * @param thrown a `Throwable` associated with the log message; * can be `null`. * * @throws NullPointerException if `level` is `null`. */ log(level: Level, msg: string, thrown: Throwable): void; /** * Logs a lazily supplied message associated with a given throwable. * * If the logger is currently enabled for the given log message level * then a message is logged that is the result produced by the * given supplier function. Otherwise, the supplier is not operated on. * * @implSpec When logging is enabled for the given level, the default * implementation for this method calls * `this.log(level, (ResourceBundle)null, msgSupplier.get(), thrown);` * * @param level one of the log message level identifiers. * @param msgSupplier a supplier function that produces a message. * @param thrown a `Throwable` associated with log message; * can be `null`. * * @throws NullPointerException if `level` is `null`, or * `msgSupplier` is `null`. */ log(level: Level, msgSupplier: Supplier, thrown: Throwable): void; /** * Logs a message with an optional list of parameters. * * @implSpec The default implementation for this method calls * `this.log(level, (ResourceBundle)null, format, params);` * * @param level one of the log message level identifiers. * @param format the string message format in {@link * java.text.MessageFormat} format, (or a key in the message * catalog, if this logger is a {@link * LoggerFinder#getLocalizedLogger(java.lang.String, * java.util.ResourceBundle, java.lang.Module) localized logger}); * can be `null`. * @param params an optional list of parameters to the message (may be * none). * * @throws NullPointerException if `level` is `null`. */ log(level: Level, format: string, ...params: any[]): void; /** * Logs a localized message associated with a given throwable. * * If the given resource bundle is non-`null`, the `msg` * string is localized using the given resource bundle. * Otherwise the `msg` string is not localized. * * @param level the log message level. * @param bundle a resource bundle to localize `msg`; can be * `null`. * @param msg the string message (or a key in the message catalog, * if `bundle` is not `null`); can be `null`. * @param thrown a `Throwable` associated with the log message; * can be `null`. * * @throws NullPointerException if `level` is `null`. */ log(level: Level, bundle: ResourceBundle, msg: string, thrown: Throwable): void; /** * Logs a message with resource bundle and an optional list of * parameters. * * If the given resource bundle is non-`null`, the `format` * string is localized using the given resource bundle. * Otherwise the `format` string is not localized. * * @param level the log message level. * @param bundle a resource bundle to localize `format`; can be * `null`. * @param format the string message format in {@link * java.text.MessageFormat} format, (or a key in the message * catalog if `bundle` is not `null`); can be `null`. * @param params an optional list of parameters to the message (may be * none). * * @throws NullPointerException if `level` is `null`. */ log(level: Level, bundle: ResourceBundle, format: string, ...params: any[]): void; } /** * The `LoggerFinder` service is responsible for creating, managing, * and configuring loggers to the underlying framework it uses. * * A logger finder is a concrete implementation of this class that has a * zero-argument constructor and implements the abstract methods defined * by this class. * The loggers returned from a logger finder are capable of routing log * messages to the logging backend this provider supports. * A given invocation of the Java Runtime maintains a single * system-wide LoggerFinder instance that is loaded as follows: * * First it finds any custom `LoggerFinder` provider * using the {@link java.util.ServiceLoader} facility with the * {@linkplain ClassLoader#getSystemClassLoader() system class * loader}. * If no `LoggerFinder` provider is found, the system default * `LoggerFinder` implementation will be used. * * * An application can replace the logging backend * even when the java.logging module is present, by simply providing * and declaring an implementation of the {@link LoggerFinder} service. * * Default Implementation * * The system default `LoggerFinder` implementation uses * `java.util.logging` as the backend framework when the * `java.logging` module is present. * It returns a {@linkplain System.Logger logger} instance * that will route log messages to a {@link java.util.logging.Logger * java.util.logging.Logger}. Otherwise, if `java.logging` is not * present, the default implementation will return a simple logger * instance that will route log messages of `INFO` level and above to * the console (`System.err`). * * Logging Configuration * * {@linkplain Logger Logger} instances obtained from the * `LoggerFinder` factory methods are not directly configurable by * the application. Configuration is the responsibility of the underlying * logging backend, and usually requires using APIs specific to that backend. * For the default `LoggerFinder` implementation * using `java.util.logging` as its backend, refer to * {@link java.util.logging java.util.logging} for logging configuration. * For the default `LoggerFinder` implementation returning simple loggers * when the `java.logging` module is absent, the configuration * is implementation dependent. * * Usually an application that uses a logging framework will log messages * through a logger facade defined (or supported) by that framework. * Applications that wish to use an external framework should log * through the facade associated with that framework. * * A system class that needs to log messages will typically obtain * a {@link System.Logger} instance to route messages to the logging * framework selected by the application. * * Libraries and classes that only need loggers to produce log messages * should not attempt to configure loggers by themselves, as that * would make them dependent from a specific implementation of the * `LoggerFinder` service. * * In addition, when a security manager is present, loggers provided to * system classes should not be directly configurable through the logging * backend without requiring permissions. * * It is the responsibility of the provider of * the concrete `LoggerFinder` implementation to ensure that * these loggers are not configured by untrusted code without proper * permission checks, as configuration performed on such loggers usually * affects all applications in the same Java Runtime. * * Message Levels and Mapping to backend levels * * A logger finder is responsible for mapping from a ` * System.Logger.Level` to a level supported by the logging backend it uses. * The default LoggerFinder using `java.util.logging` as the backend * maps `System.Logger` levels to * {@linkplain java.util.logging.Level java.util.logging} levels * of corresponding severity - as described in {@link Logger.Level * Logger.Level}. * * @see java.lang.System * @see java.lang.System.Logger * * @since 9 */ export class LoggerFinder { /** * Returns an instance of {@link Logger Logger} * for the given `module`. * * @param name the name of the logger. * @param module the module for which the logger is being requested. * * @return a {@link Logger logger} suitable for use within the given * module. * @throws NullPointerException if `name` is `null` or * `module` is `null`. * @throws SecurityException if a security manager is present and its * `checkPermission` method doesn't allow the * `RuntimePermission("loggerFinder")`. */ getLogger(name: string, module: Module): Logger; /** * Returns a localizable instance of {@link Logger Logger} * for the given `module`. * The returned logger will use the provided resource bundle for * message localization. * * @implSpec By default, this method calls {@link * #getLogger(java.lang.String, java.lang.Module) * this.getLogger(name, module)} to obtain a logger, then wraps that * logger in a {@link Logger} instance where all methods that do not * take a {@link ResourceBundle} as parameter are redirected to one * which does - passing the given `bundle` for * localization. So for instance, a call to {@link * Logger#log(Logger.Level, String) Logger.log(Level.INFO, msg)} * will end up as a call to {@link * Logger#log(Logger.Level, ResourceBundle, String, Object...) * Logger.log(Level.INFO, bundle, msg, (Object[])null)} on the wrapped * logger instance. * Note however that by default, string messages returned by {@link * java.util.function.Supplier Supplier} will not be * localized, as it is assumed that such strings are messages which are * already constructed, rather than keys in a resource bundle. * * An implementation of `LoggerFinder` may override this method, * for example, when the underlying logging backend provides its own * mechanism for localizing log messages, then such a * `LoggerFinder` would be free to return a logger * that makes direct use of the mechanism provided by the backend. * * @param name the name of the logger. * @param bundle a resource bundle; can be `null`. * @param module the module for which the logger is being requested. * @return an instance of {@link Logger Logger} which will use the * provided resource bundle for message localization. * * @throws NullPointerException if `name` is `null` or * `module` is `null`. * @throws SecurityException if a security manager is present and its * `checkPermission` method doesn't allow the * `RuntimePermission("loggerFinder")`. */ getLocalizedLogger(name: string, bundle: ResourceBundle, module: Module): Logger; /** * Returns the `LoggerFinder` instance. There is one * single system-wide `LoggerFinder` instance in * the Java Runtime. See the class specification of how the * {@link LoggerFinder LoggerFinder} implementation is located and * loaded. * * @return the {@link LoggerFinder LoggerFinder} instance. * @throws SecurityException if a security manager is present and its * `checkPermission` method doesn't allow the * `RuntimePermission("loggerFinder")`. */ static get loggerFinder(): LoggerFinder; } } declare module 'java.lang.module.ModuleDescriptor.Requires' { import { Enum } from 'java.lang'; /** * A modifier on a module dependence. * * @see Requires#modifiers() * @since 9 */ export class Modifier extends Enum { /** * The dependence causes any module which depends on the current * module to have an implicitly declared dependence on the module * named by the `Requires`. */ static readonly TRANSITIVE: Modifier; /** * The dependence is mandatory in the static phase, during compilation, * but is optional in the dynamic phase, during execution. */ static readonly STATIC: Modifier; /** * The dependence was not explicitly or implicitly declared in the * source of the module declaration. */ static readonly SYNTHETIC: Modifier; /** * The dependence was implicitly declared in the source of the module * declaration. */ static readonly MANDATED: Modifier; static valueOf(name: string): Modifier; static values(): Modifier[]; } } declare module 'java.lang.ref' { import { Runnable } from 'java.lang'; import { ThreadFactory } from 'java.util.concurrent'; import { Cleanable } from 'java.lang.ref.Cleaner'; import { Lock } from 'java.lang.ref.ReferenceQueue'; export class WeakReference extends Reference { /** * Creates a new weak reference that refers to the given object. The new * reference is not registered with any queue. * * @param referent object the new weak reference will refer to */ constructor(referent: T); /** * Creates a new weak reference that refers to the given object and is * registered with the given queue. * * @param referent object the new weak reference will refer to * @param q the queue with which the reference is to be registered, * or `null` if registration is not required */ constructor(referent: T, q: ReferenceQueue); } /** * `Cleaner` manages a set of object references and corresponding cleaning actions. * * Cleaning actions are {@link #register(Object object, Runnable action) registered} * to run after the cleaner is notified that the object has become * phantom reachable. * The cleaner uses {@link PhantomReference} and {@link ReferenceQueue} to be * notified when the reachability * changes. * * Each cleaner operates independently, managing the pending cleaning actions * and handling threading and termination when the cleaner is no longer in use. * Registering an object reference and corresponding cleaning action returns * a {@link Cleanable Cleanable}. The most efficient use is to explicitly invoke * the {@link Cleanable#clean clean} method when the object is closed or * no longer needed. * The cleaning action is a {@link Runnable} to be invoked at most once when * the object has become phantom reachable unless it has already been explicitly cleaned. * Note that the cleaning action must not refer to the object being registered. * If so, the object will not become phantom reachable and the cleaning action * will not be invoked automatically. * * The execution of the cleaning action is performed * by a thread associated with the cleaner. * All exceptions thrown by the cleaning action are ignored. * The cleaner and other cleaning actions are not affected by * exceptions in a cleaning action. * The thread runs until all registered cleaning actions have * completed and the cleaner itself is reclaimed by the garbage collector. * * The behavior of cleaners during {@link System#exit(int) System.exit} * is implementation specific. No guarantees are made relating * to whether cleaning actions are invoked or not. * * Unless otherwise noted, passing a `null` argument to a constructor or * method in this class will cause a * {@link java.lang.NullPointerException NullPointerException} to be thrown. * * @apiNote * The cleaning action is invoked only after the associated object becomes * phantom reachable, so it is important that the object implementing the * cleaning action does not hold references to the object. * In this example, a static class encapsulates the cleaning state and action. * An "inner" class, anonymous or not, must not be used because it implicitly * contains a reference to the outer instance, preventing it from becoming * phantom reachable. * The choice of a new cleaner or sharing an existing cleaner is determined * by the use case. * * If the CleaningExample is used in a try-finally block then the * `close` method calls the cleaning action. * If the `close` method is not called, the cleaning action is called * by the Cleaner when the CleaningExample instance has become phantom reachable. * {@code * public class CleaningExample implements AutoCloseable { * // A cleaner, preferably one shared within a library * private static final Cleaner cleaner = ; * * static class State implements Runnable { * * State(...) { * // initialize State needed for cleaning action * } * * public void run() { * // cleanup action accessing State, executed at most once * } * } * * private final State state; * private final Cleaner.Cleanable cleanable; * * public CleaningExample() { * this.state = new State(...); * this.cleanable = cleaner.register(this, state); * } * * public void close() { * cleanable.clean(); * } * } * } * The cleaning action could be a lambda but all too easily will capture * the object reference, by referring to fields of the object being cleaned, * preventing the object from becoming phantom reachable. * Using a static nested class, as above, will avoid accidentally retaining the * object reference. * * * Cleaning actions should be prepared to be invoked concurrently with * other cleaning actions. * Typically the cleaning actions should be very quick to execute * and not block. If the cleaning action blocks, it may delay processing * other cleaning actions registered to the same cleaner. * All cleaning actions registered to a cleaner should be mutually compatible. * @since 9 */ export class Cleaner { /** * Returns a new `Cleaner`. * * The cleaner creates a {@link Thread#setDaemon(boolean) daemon thread} * to process the phantom reachable objects and to invoke cleaning actions. * The {@linkplain java.lang.Thread#getContextClassLoader context class loader} * of the thread is set to the * {@link ClassLoader#getSystemClassLoader() system class loader}. * The thread has no permissions, enforced only if a * {@link java.lang.System#setSecurityManager(SecurityManager) SecurityManager is set}. * * The cleaner terminates when it is phantom reachable and all of the * registered cleaning actions are complete. * * @return a new `Cleaner` * * @throws SecurityException if the current thread is not allowed to * create or start the thread. */ static create(): Cleaner; /** * Returns a new `Cleaner` using a `Thread` from the `ThreadFactory`. * * A thread from the thread factory's {@link ThreadFactory#newThread(Runnable) newThread} * method is set to be a {@link Thread#setDaemon(boolean) daemon thread} * and started to process phantom reachable objects and invoke cleaning actions. * On each call the {@link ThreadFactory#newThread(Runnable) thread factory} * must provide a Thread that is suitable for performing the cleaning actions. * * The cleaner terminates when it is phantom reachable and all of the * registered cleaning actions are complete. * * @param threadFactory a `ThreadFactory` to return a new `Thread` * to process cleaning actions * @return a new `Cleaner` * * @throws IllegalThreadStateException if the thread from the thread * factory was {@link Thread.State#NEW not a new thread}. * @throws SecurityException if the current thread is not allowed to * create or start the thread. */ static create(threadFactory: ThreadFactory): Cleaner; /** * Registers an object and a cleaning action to run when the object * becomes phantom reachable. * Refer to the API Note above for * cautions about the behavior of cleaning actions. * * @param obj the object to monitor * @param action a `Runnable` to invoke when the object becomes phantom reachable * @return a `Cleanable` instance */ register(obj: any, action: Runnable): Cleanable; } export class PhantomReference extends Reference { /** * Returns this reference object's referent. Because the referent of a * phantom reference is always inaccessible, this method always returns * `null`. * * @return `null` */ get(): T; /** * Creates a new phantom reference that refers to the given object and * is registered with the given queue. * * It is possible to create a phantom reference with a `null` * queue, but such a reference is completely useless: Its `get` * method will always return `null` and, since it does not have a queue, * it will never be enqueued. * * @param referent the object the new phantom reference will refer to * @param q the queue with which the reference is to be registered, * or `null` if registration is not required */ constructor(referent: T, q: ReferenceQueue); } export class SoftReference extends Reference { /** * Creates a new soft reference that refers to the given object. The new * reference is not registered with any queue. * * @param referent object the new soft reference will refer to */ constructor(referent: T); /** * Creates a new soft reference that refers to the given object and is * registered with the given queue. * * @param referent object the new soft reference will refer to * @param q the queue with which the reference is to be registered, * or `null` if registration is not required * */ constructor(referent: T, q: ReferenceQueue); /** * Returns this reference object's referent. If this reference object has * been cleared, either by the program or by the garbage collector, then * this method returns `null`. * * @return The object to which this reference refers, or * `null` if this reference object has been cleared */ get(): T; } export class Reference { /** * Returns this reference object's referent. If this reference object has * been cleared, either by the program or by the garbage collector, then * this method returns `null`. * * @apiNote * This method returns a strong reference to the referent. This may cause * the garbage collector to treat it as strongly reachable until some later * collection cycle. The {@link #refersTo(Object) refersTo} method can be * used to avoid such strengthening when testing whether some object is * the referent of a reference object; that is, use `ref.refersTo(obj)` * rather than `ref.get() == obj`. * * @return The object to which this reference refers, or * `null` if this reference object has been cleared * @see #refersTo */ get(): T; /** * Tests if the referent of this reference object is `obj`. * Using a `null` `obj` returns `true` if the * reference object has been cleared. * * @param obj the object to compare with this reference object's referent * @return `true` if `obj` is the referent of this reference object * @since 16 */ refersTo(obj: T): boolean; /** * Clears this reference object. Invoking this method will not cause this * object to be enqueued. * * This method is invoked only by Java code; when the garbage collector * clears references it does so directly, without invoking this method. */ clear(): void; /** * Tests if this reference object is in its associated queue, if any. * This method returns `true` only if all of the following conditions * are met: * * this reference object was registered with a queue when it was created; and * the garbage collector has added this reference object to the queue * or {@link #enqueue()} is called; and * this reference object is not yet removed from the queue. * * Otherwise, this method returns `false`. * This method may return `false` if this reference object has been cleared * but not enqueued due to the race condition. * * @deprecated * This method was originally specified to test if a reference object has * been cleared and enqueued but was never implemented to do this test. * This method could be misused due to the inherent race condition * or without an associated `ReferenceQueue`. * An application relying on this method to release critical resources * could cause serious performance issue. * An application should use {@link ReferenceQueue} to reliably determine * what reference objects that have been enqueued or * {@link #refersTo(Object) refersTo(null)} to determine if this reference * object has been cleared. * * @return `true` if and only if this reference object is * in its associated queue (if any). */ isEnqueued(): boolean; /** * Clears this reference object and adds it to the queue with which * it is registered, if any. * * This method is invoked only by Java code; when the garbage collector * enqueues references it does so directly, without invoking this method. * * @return `true` if this reference object was successfully * enqueued; `false` if it was already enqueued or if * it was not registered with a queue when it was created */ enqueue(): boolean; /** * Ensures that the object referenced by the given reference remains * strongly reachable, * regardless of any prior actions of the program that might otherwise cause * the object to become unreachable; thus, the referenced object is not * reclaimable by garbage collection at least until after the invocation of * this method. Invocation of this method does not itself initiate garbage * collection or finalization. * * This method establishes an ordering for * strong reachability * with respect to garbage collection. It controls relations that are * otherwise only implicit in a program -- the reachability conditions * triggering garbage collection. This method is designed for use in * uncommon situations of premature finalization where using * `synchronized` blocks or methods, or using other synchronization * facilities are not possible or do not provide the desired control. This * method is applicable only when reclamation may have visible effects, * which is possible for objects with finalizers (See Section {@jls 12.6} * of The Java Language Specification) that * are implemented in ways that rely on ordering control for * correctness. * * @apiNote * Finalization may occur whenever the virtual machine detects that no * reference to an object will ever be stored in the heap: The garbage * collector may reclaim an object even if the fields of that object are * still in use, so long as the object has otherwise become unreachable. * This may have surprising and undesirable effects in cases such as the * following example in which the bookkeeping associated with a class is * managed through array indices. Here, method `action` uses a * `reachabilityFence` to ensure that the `Resource` object is * not reclaimed before bookkeeping on an associated * `ExternalResource` has been performed; in particular here, to * ensure that the array slot holding the `ExternalResource` is not * nulled out in method {@link Object#finalize}, which may otherwise run * concurrently. * * {@code * class Resource { * private static ExternalResource[] externalResourceArray = ... * * int myIndex; * Resource(...) { * myIndex = ... * externalResourceArray[myIndex] = ...; * ... * } * protected void finalize() { * externalResourceArray[myIndex] = null; * ... * } * public void action() { * try { * // ... * int i = myIndex; * Resource.update(externalResourceArray[i]); * } finally { * Reference.reachabilityFence(this); * } * } * private static void update(ExternalResource ext) { * ext.status = ...; * } * }} * * Here, the invocation of `reachabilityFence` is nonintuitively * placed after the call to `update`, to ensure that the * array slot is not nulled out by {@link Object#finalize} before the * update, even if the call to `action` was the last use of this * object. This might be the case if, for example a usage in a user program * had the form `new Resource().action();` which retains no other * reference to this `Resource`. While probably overkill here, * `reachabilityFence` is placed in a `finally` block to ensure * that it is invoked across all paths in the method. In a method with more * complex control paths, you might need further precautions to ensure that * `reachabilityFence` is encountered along all of them. * * It is sometimes possible to better encapsulate use of * `reachabilityFence`. Continuing the above example, if it were * acceptable for the call to method `update` to proceed even if the * finalizer had already executed (nulling out slot), then you could * localize use of `reachabilityFence`: * * {@code * public void action2() { * // ... * Resource.update(getExternalResource()); * } * private ExternalResource getExternalResource() { * ExternalResource ext = externalResourceArray[myIndex]; * Reference.reachabilityFence(this); * return ext; * }} * * Method `reachabilityFence` is not required in constructions * that themselves ensure reachability. For example, because objects that * are locked cannot, in general, be reclaimed, it would suffice if all * accesses of the object, in all methods of class `Resource` * (including `finalize`) were enclosed in `synchronized (this)` * blocks. (Further, such blocks must not include infinite loops, or * themselves be unreachable, which fall into the corner case exceptions to * the "in general" disclaimer.) However, method `reachabilityFence` * remains a better option in cases where this approach is not as efficient, * desirable, or possible; for example because it would encounter deadlock. * * @param ref the reference. If `null`, this method has no effect. * @since 9 * @jls 12.6 Finalization of Class Instances */ static reachabilityFence(ref: any): void; } export class ReferenceQueue { /** * Constructs a new reference-object queue. */ constructor(); /** * Polls this queue to see if a reference object is available. If one is * available without further delay then it is removed from the queue and * returned. Otherwise this method immediately returns `null`. * * @return A reference object, if one was immediately available, * otherwise `null` */ poll(): Reference; /** * Removes the next reference object in this queue, blocking until either * one becomes available or the given timeout period expires. * * This method does not offer real-time guarantees: It schedules the * timeout as if by invoking the {@link Object#wait(long)} method. * * @param timeout If positive, block for up to `timeout` * milliseconds while waiting for a reference to be * added to this queue. If zero, block indefinitely. * * @return A reference object, if one was available within the specified * timeout period, otherwise `null` * * @throws IllegalArgumentException * If the value of the timeout argument is negative * * @throws InterruptedException * If the timeout wait is interrupted */ remove(timeout: number): Reference; /** * Removes the next reference object in this queue, blocking until one * becomes available. * * @return A reference object, blocking until one becomes available * @throws InterruptedException If the wait is interrupted */ remove(): Reference; } } declare module 'java.lang.Enum' { import { DynamicConstantDesc, ClassDesc } from 'java.lang.constant'; import { Lookup } from 'java.lang.invoke.MethodHandles'; /** * A nominal descriptor for an * `enum` constant. * * @param the type of the enum constant * * @since 12 */ export class EnumDesc extends DynamicConstantDesc { /** * Returns a nominal descriptor for the specified `enum` class and name * * @param the type of the enum constant * @param enumClass a {@link ClassDesc} describing the `enum` class * @param constantName the unqualified name of the enum constant * @return the nominal descriptor * @throws NullPointerException if any argument is null * @jvms 4.2.2 Unqualified Names * @since 12 */ static of(enumClass: ClassDesc, constantName: string): EnumDesc; resolveConstantDesc(lookup: Lookup): E; toString(): string; } } declare module 'java.lang.Thread' { import { Enum, Throwable, Thread } from 'java.lang'; /** * A thread state. A thread can be in one of the following states: * * {@link #NEW} * A thread that has not yet started is in this state. * * {@link #RUNNABLE} * A thread executing in the Java virtual machine is in this state. * * {@link #BLOCKED} * A thread that is blocked waiting for a monitor lock * is in this state. * * {@link #WAITING} * A thread that is waiting indefinitely for another thread to * perform a particular action is in this state. * * {@link #TIMED_WAITING} * A thread that is waiting for another thread to perform an action * for up to a specified waiting time is in this state. * * {@link #TERMINATED} * A thread that has exited is in this state. * * * * * A thread can be in only one state at a given point in time. * These states are virtual machine states which do not reflect * any operating system thread states. * * @since 1.5 * @see #getState */ export class State extends Enum { /** * Thread state for a thread which has not yet started. */ static readonly NEW: State; /** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */ static readonly RUNNABLE: State; /** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * {@link Object#wait() Object.wait}. */ static readonly BLOCKED: State; /** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * * {@link Object#wait() Object.wait} with no timeout * {@link #join() Thread.join} with no timeout * {@link LockSupport#park() LockSupport.park} * * * A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called `Object.wait()` * on an object is waiting for another thread to call * `Object.notify()` or `Object.notifyAll()` on * that object. A thread that has called `Thread.join()` * is waiting for a specified thread to terminate. */ static readonly WAITING: State; /** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * * {@link #sleep Thread.sleep} * {@link Object#wait(long) Object.wait} with timeout * {@link #join(long) Thread.join} with timeout * {@link LockSupport#parkNanos LockSupport.parkNanos} * {@link LockSupport#parkUntil LockSupport.parkUntil} * */ static readonly TIMED_WAITING: State; /** * Thread state for a terminated thread. * The thread has completed execution. */ static readonly TERMINATED: State; static valueOf(name: string): State; static values(): State[]; } /** * Interface for handlers invoked when a `Thread` abruptly * terminates due to an uncaught exception. * When a thread is about to terminate due to an uncaught exception * the Java Virtual Machine will query the thread for its * `UncaughtExceptionHandler` using * {@link #getUncaughtExceptionHandler} and will invoke the handler's * `uncaughtException` method, passing the thread and the * exception as arguments. * If a thread has not had its `UncaughtExceptionHandler` * explicitly set, then its `ThreadGroup` object acts as its * `UncaughtExceptionHandler`. If the `ThreadGroup` object * has no * special requirements for dealing with the exception, it can forward * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler * default uncaught exception handler}. * * @see #setDefaultUncaughtExceptionHandler * @see #setUncaughtExceptionHandler * @see ThreadGroup#uncaughtException * @since 1.5 */ export class UncaughtExceptionHandler { /** * Method invoked when the given thread terminates due to the * given uncaught exception. * Any exception thrown by this method will be ignored by the * Java Virtual Machine. * @param t the thread * @param e the exception */ uncaughtException(t: Thread, e: Throwable): void; } } declare module 'java.lang.invoke.TypeDescriptor' { import { List } from 'java.util'; import { TypeDescriptor } from 'java.lang.invoke'; /** * An entity that has a field type descriptor. * Field descriptors conforming to JVMS {@jvms 4.3.2} can be described * nominally via {@link Class#describeConstable Class::describeConstable}; * otherwise they cannot be described nominally. * * @param the class implementing {@linkplain TypeDescriptor.OfField} * @jvms 4.3.2 Field Descriptors * @since 12 */ export class OfField extends TypeDescriptor { /** * Does this field descriptor describe an array type? * @return whether this field descriptor describes an array type */ isArray(): boolean; /** * Does this field descriptor describe a primitive type (including void.) * * @return whether this field descriptor describes a primitive type */ isPrimitive(): boolean; /** * If this field descriptor describes an array type, return * a descriptor for its component type, otherwise return `null`. * @return the component type, or `null` if this field descriptor does * not describe an array type */ componentType(): F; /** * Return a descriptor for the array type whose component type is described by this * descriptor * @return the descriptor for the array type */ arrayType(): F; } /** * An entity that has a method type descriptor * Method descriptors conforming to JVMS {@jvms 4.3.3} can be described * nominally via {@link MethodType#describeConstable MethodType::describeConstable}; * otherwise they cannot be described nominally. * * @param the type representing field type descriptors * @param the class implementing {@linkplain TypeDescriptor.OfMethod} * @jvms 4.3.2 Field Descriptors * @jvms 4.3.3 Method Descriptors * @since 12 */ export class OfMethod extends TypeDescriptor { /** * Return the number of parameters in the method type * @return the number of parameters */ parameterCount(): number; /** * Return a field descriptor describing the requested parameter of the method type * described by this descriptor * @param i the index of the parameter * @return a field descriptor for the requested parameter type * @throws IndexOutOfBoundsException if the index is outside the half-open * range {[0, parameterCount)} */ parameterType(i: number): F; /** * Return a field descriptor describing the return type of the method type described * by this descriptor * @return a field descriptor for the return type */ returnType(): F; /** * Return an array of field descriptors for the parameter types of the method type * described by this descriptor * @return field descriptors for the parameter types */ parameterArray(): F[]; /** * Return an immutable list of field descriptors for the parameter types of the method type * described by this descriptor * @return field descriptors for the parameter types */ parameterList(): F[]; /** * Return a method descriptor that is identical to this one, except that the return * type has been changed to the specified type * * @param newReturn a field descriptor for the new return type * @throws NullPointerException if any argument is `null` * @return the new method descriptor */ changeReturnType(newReturn: F): M; /** * Return a method descriptor that is identical to this one, * except that a single parameter type has been changed to the specified type. * * @param index the index of the parameter to change * @param paramType a field descriptor describing the new parameter type * @return the new method descriptor * @throws NullPointerException if any argument is `null` * @throws IndexOutOfBoundsException if the index is outside the half-open * range {[0, parameterCount)} */ changeParameterType(index: number, paramType: F): M; /** * Return a method descriptor that is identical to this one, * except that a range of parameter types have been removed. * * @param start the index of the first parameter to remove * @param end the index after the last parameter to remove * @return the new method descriptor * * @throws IndexOutOfBoundsException if `start` is outside the half-open * range `[0, parameterCount)`, or `end` is outside the closed range * `[0, parameterCount]`, or if `start > end` */ dropParameterTypes(start: number, end: number): M; /** * Return a method descriptor that is identical to this one, * except that a range of additional parameter types have been inserted. * * @param pos the index at which to insert the first inserted parameter * @param paramTypes field descriptors describing the new parameter types * to insert * @return the new method descriptor * @throws NullPointerException if any argument is `null` * @throws IndexOutOfBoundsException if `pos` is outside the closed * range {[0, parameterCount]} */ insertParameterTypes(pos: number, ...paramTypes: F[]): M; } } declare module 'java.lang.reflect' { import { BasicPermission } from 'java.security'; import { Map } from 'java.util'; import { ClassFormatError, ReflectiveOperationException, RuntimeException, ClassValue, Throwable, ClassLoader, Class } from 'java.lang'; import { Serializable, ObjectStreamField } from 'java.io'; import { ConcurrentHashMap } from 'java.util.concurrent'; import { Annotation } from 'java.lang.annotation'; import { MethodHandle } from 'java.lang.invoke'; /** * `Constructor` provides information about, and access to, a single * constructor for a class. * * `Constructor` permits widening conversions to occur when matching the * actual parameters to newInstance() with the underlying * constructor's formal parameters, but throws an * `IllegalArgumentException` if a narrowing conversion would occur. * * @param the class in which the constructor is declared * * @see Member * @see java.lang.Class * @see java.lang.Class#getConstructors() * @see java.lang.Class#getConstructor(Class[]) * @see java.lang.Class#getDeclaredConstructors() * * @author Kenneth Russell * @author Nakul Saraiya * @since 1.1 */ export class Constructor extends Executable { /** * {@inheritDoc} * * A `SecurityException` is also thrown if this object is a * `Constructor` object for the class `Class` and `flag` * is true. * * @param flag {@inheritDoc} * * @throws InaccessibleObjectException {@inheritDoc} * @throws SecurityException if the request is denied by the security manager * or this is a constructor for `java.lang.Class` * */ setAccessible(flag: boolean): void; /** * Returns the `Class` object representing the class that * declares the constructor represented by this object. */ get declaringClass(): Class; /** * Returns the name of this constructor, as a string. This is * the binary name of the constructor's declaring class. */ get name(): string; /** * {@inheritDoc} */ get modifiers(): number; /** * {@inheritDoc} * @throws GenericSignatureFormatError {@inheritDoc} * @since 1.5 */ get typeParameters(): TypeVariable[]; /** * {@inheritDoc} */ get parameterTypes(): Class[]; /** * {@inheritDoc} * @since 1.8 */ get parameterCount(): number; /** * {@inheritDoc} * @throws GenericSignatureFormatError {@inheritDoc} * @throws TypeNotPresentException {@inheritDoc} * @throws MalformedParameterizedTypeException {@inheritDoc} * @since 1.5 */ get genericParameterTypes(): Type[]; /** * {@inheritDoc} */ get exceptionTypes(): Class[]; /** * {@inheritDoc} * @throws GenericSignatureFormatError {@inheritDoc} * @throws TypeNotPresentException {@inheritDoc} * @throws MalformedParameterizedTypeException {@inheritDoc} * @since 1.5 */ get genericExceptionTypes(): Type[]; /** * Compares this `Constructor` against the specified object. * Returns true if the objects are the same. Two `Constructor` objects are * the same if they were declared by the same class and have the * same formal parameter types. */ equals(obj: any): boolean; /** * Returns a hashcode for this `Constructor`. The hashcode is * the same as the hashcode for the underlying constructor's * declaring class name. */ hashCode(): number; /** * Returns a string describing this `Constructor`. The string is * formatted as the constructor access modifiers, if any, * followed by the fully-qualified name of the declaring class, * followed by a parenthesized, comma-separated list of the * constructor's formal parameter types. For example: * {@code * public java.util.Hashtable(int,float) * } * * If the constructor is declared to throw exceptions, the * parameter list is followed by a space, followed by the word * "`throws`" followed by a comma-separated list of the * thrown exception types. * * The only possible modifiers for constructors are the access * modifiers `public`, `protected` or * `private`. Only one of these may appear, or none if the * constructor has default (package) access. * * @return a string describing this `Constructor` * @jls 8.8.3 Constructor Modifiers * @jls 8.9.2 Enum Body Declarations */ toString(): string; /** * Returns a string describing this `Constructor`, * including type parameters. The string is formatted as the * constructor access modifiers, if any, followed by an * angle-bracketed comma separated list of the constructor's type * parameters, if any, including informative bounds of the * type parameters, if any, followed by the fully-qualified name of the * declaring class, followed by a parenthesized, comma-separated * list of the constructor's generic formal parameter types. * * If this constructor was declared to take a variable number of * arguments, instead of denoting the last parameter as * "Type[]", it is denoted as * "Type...". * * A space is used to separate access modifiers from one another * and from the type parameters or class name. If there are no * type parameters, the type parameter list is elided; if the type * parameter list is present, a space separates the list from the * class name. If the constructor is declared to throw * exceptions, the parameter list is followed by a space, followed * by the word "`throws`" followed by a * comma-separated list of the generic thrown exception types. * * The only possible modifiers for constructors are the access * modifiers `public`, `protected` or * `private`. Only one of these may appear, or none if the * constructor has default (package) access. * * @return a string describing this `Constructor`, * include type parameters * * @since 1.5 * @jls 8.8.3 Constructor Modifiers * @jls 8.9.2 Enum Body Declarations */ toGenericString(): string; /** * Uses the constructor represented by this `Constructor` object to * create and initialize a new instance of the constructor's * declaring class, with the specified initialization parameters. * Individual parameters are automatically unwrapped to match * primitive formal parameters, and both primitive and reference * parameters are subject to method invocation conversions as necessary. * * If the number of formal parameters required by the underlying constructor * is 0, the supplied `initargs` array may be of length 0 or null. * * If the constructor's declaring class is an inner class in a * non-static context, the first argument to the constructor needs * to be the enclosing instance; see section {@jls 15.9.3} of * The Java Language Specification. * * If the required access and argument checks succeed and the * instantiation will proceed, the constructor's declaring class * is initialized if it has not already been initialized. * * If the constructor completes normally, returns the newly * created and initialized instance. * * @param initargs array of objects to be passed as arguments to * the constructor call; values of primitive types are wrapped in * a wrapper object of the appropriate type (e.g. a `float` * in a {@link java.lang.Float Float}) * * @return a new object created by calling the constructor * this object represents * * @throws IllegalAccessException if this `Constructor` object * is enforcing Java language access control and the underlying * constructor is inaccessible. * @throws IllegalArgumentException if the number of actual * and formal parameters differ; if an unwrapping * conversion for primitive arguments fails; or if, * after possible unwrapping, a parameter value * cannot be converted to the corresponding formal * parameter type by a method invocation conversion; if * this constructor pertains to an enum class. * @throws InstantiationException if the class that declares the * underlying constructor represents an abstract class. * @throws InvocationTargetException if the underlying constructor * throws an exception. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. */ newInstance(...initargs: any[]): T; /** * {@inheritDoc} * @since 1.5 */ isVarArgs(): boolean; /** * {@inheritDoc} * @jls 13.1 The Form of a Binary * @since 1.5 */ isSynthetic(): boolean; /** * {@inheritDoc} * * @throws NullPointerException {@inheritDoc} * @since 1.5 */ getAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * @since 1.5 */ get declaredAnnotations(): Annotation[]; /** * {@inheritDoc} * @since 1.5 */ get parameterAnnotations(): Annotation[][]; /** * {@inheritDoc} * @since 1.8 */ get annotatedReturnType(): AnnotatedType; /** * {@inheritDoc} * @since 1.8 */ get annotatedReceiverType(): AnnotatedType; /** * Convenience method to set the `accessible` flag for an * array of reflected objects with a single security check (for efficiency). * * This method may be used to enable access to all reflected objects in * the array when access to each reflected object can be enabled as * specified by {@link #setAccessible(boolean) setAccessible(boolean)}. * * If there is a security manager, its * `checkPermission` method is first called with a * `ReflectPermission("suppressAccessChecks")` permission. * * A `SecurityException` is also thrown if any of the elements of * the input `array` is a {@link java.lang.reflect.Constructor} * object for the class `java.lang.Class` and `flag` is true. * * @param array the array of AccessibleObjects * @param flag the new value for the `accessible` flag * in each object * @throws InaccessibleObjectException if access cannot be enabled for all * objects in the array * @throws SecurityException if the request is denied by the security manager * or an element in the array is a constructor for ` * java.lang.Class` * @see SecurityManager#checkPermission * @see ReflectPermission * @revised 9 */ static setAccessible(array: AccessibleObject[], flag: boolean): void; /** * {@inheritDoc} * * Note that any annotations returned by this method are * declaration annotations. * * @since 1.5 */ get annotations(): Annotation[]; } /** * TypeVariable is the common superinterface for type variables of kinds. * A type variable is created the first time it is needed by a reflective * method, as specified in this package. If a type variable t is referenced * by a type (i.e, class, interface or annotation type) T, and T is declared * by the nth enclosing class of T (see JLS 8.1.2), then the creation of t * requires the resolution (see JVMS 5) of the ith enclosing class of T, * for i = 0 to n, inclusive. Creating a type variable must not cause the * creation of its bounds. Repeated creation of a type variable has no effect. * * Multiple objects may be instantiated at run-time to * represent a given type variable. Even though a type variable is * created only once, this does not imply any requirement to cache * instances representing the type variable. However, all instances * representing a type variable must be equal() to each other. * As a consequence, users of type variables must not rely on the identity * of instances of classes implementing this interface. * * @param the type of generic declaration that declared the * underlying type variable. * * @jls 4.4 Type Variables * @since 1.5 */ export class TypeVariable extends Type { /** * Returns an array of `Type` objects representing the * upper bound(s) of this type variable. If no upper bound is * explicitly declared, the upper bound is `Object`. * * For each upper bound B: if B is a parameterized * type or a type variable, it is created, (see {@link * java.lang.reflect.ParameterizedType ParameterizedType} for the * details of the creation process for parameterized types). * Otherwise, B is resolved. * * @throws TypeNotPresentException if any of the * bounds refers to a non-existent type declaration * @throws MalformedParameterizedTypeException if any of the * bounds refer to a parameterized type that cannot be instantiated * for any reason * @return an array of `Type`s representing the upper * bound(s) of this type variable */ get bounds(): Type[]; /** * Returns the `GenericDeclaration` object representing the * generic declaration declared for this type variable. * * @return the generic declaration declared for this type variable. * * @since 1.5 */ get genericDeclaration(): D; /** * Returns the name of this type variable, as it occurs in the source code. * * @return the name of this type variable, as it appears in the source code */ get name(): string; /** * Returns an array of AnnotatedType objects that represent the use of * types to denote the upper bounds of the type parameter represented by * this TypeVariable. The order of the objects in the array corresponds to * the order of the bounds in the declaration of the type parameter. Note that * if no upper bound is explicitly declared, the upper bound is unannotated * `Object`. * * @return an array of objects representing the upper bound(s) of the type variable * @since 1.8 */ get annotatedBounds(): AnnotatedType[]; } export interface TypeVariable extends Type, AnnotatedElement {} /** * ParameterizedType represents a parameterized type such as * `Collection`. * * A parameterized type is created the first time it is needed by a * reflective method, as specified in this package. When a * parameterized type p is created, the generic class or interface declaration * that p instantiates is resolved, and all type arguments of p are created * recursively. See {@link java.lang.reflect.TypeVariable * TypeVariable} for details on the creation process for type * variables. Repeated creation of a parameterized type has no effect. * * Instances of classes that implement this interface must implement * an equals() method that equates any two instances that share the * same generic class or interface declaration and have equal type parameters. * * @jls 4.5 Parameterized Types * @since 1.5 */ export class ParameterizedType extends Type { /** * Returns an array of `Type` objects representing the actual type * arguments to this type. * * Note that in some cases, the returned array be empty. This can occur * if this type represents a non-parameterized type nested within * a parameterized type. * * @return an array of `Type` objects representing the actual type * arguments to this type * @throws TypeNotPresentException if any of the actual type arguments * refers to a non-existent class or interface declaration * @throws MalformedParameterizedTypeException if any of the * actual type parameters refer to a parameterized type that cannot * be instantiated for any reason * @since 1.5 */ get actualTypeArguments(): Type[]; /** * Returns the `Type` object representing the class or interface * that declared this type. * * @return the `Type` object representing the class or interface * that declared this type * @since 1.5 */ get rawType(): Type; /** * Returns a `Type` object representing the type that this type * is a member of. For example, if this type is `O.I`, * return a representation of `O`. * * If this type is a top-level type, `null` is returned. * * @return a `Type` object representing the type that * this type is a member of. If this type is a top-level type, * `null` is returned * @throws TypeNotPresentException if the owner type * refers to a non-existent class or interface declaration * @throws MalformedParameterizedTypeException if the owner type * refers to a parameterized type that cannot be instantiated * for any reason * @since 1.5 */ get ownerType(): Type; } /** * The `Array` class provides static methods to dynamically create and * access Java arrays. * * `Array` permits widening conversions to occur during a get or set * operation, but throws an `IllegalArgumentException` if a narrowing * conversion would occur. * * @author Nakul Saraiya * @since 1.1 */ export class Array { /** * Creates a new array with the specified component type and * length. * Invoking this method is equivalent to creating an array * as follows: * * * int[] x = {length}; * Array.newInstance(componentType, x); * * * * The number of dimensions of the new array must not * exceed 255. * * @param componentType the `Class` object representing the * component type of the new array * @param length the length of the new array * @return the new array * @throws NullPointerException if the specified * `componentType` parameter is null * @throws IllegalArgumentException if componentType is {@link * Void#TYPE} or if the number of dimensions of the requested array * instance exceed 255. * @throws NegativeArraySizeException if the specified `length` * is negative */ static newInstance(componentType: Class, length: number): any; /** * Creates a new array * with the specified component type and dimensions. * If `componentType` * represents a non-array class or interface, the new array * has `dimensions.length` dimensions and * `componentType` as its component type. If * `componentType` represents an array class, the * number of dimensions of the new array is equal to the sum * of `dimensions.length` and the number of * dimensions of `componentType`. In this case, the * component type of the new array is the component type of * `componentType`. * * The number of dimensions of the new array must not * exceed 255. * * @param componentType the `Class` object representing the component * type of the new array * @param dimensions an array of `int` representing the dimensions of * the new array * @return the new array * @throws NullPointerException if the specified * `componentType` argument is null * @throws IllegalArgumentException if the specified `dimensions` * argument is a zero-dimensional array, if componentType is {@link * Void#TYPE}, or if the number of dimensions of the requested array * instance exceed 255. * @throws NegativeArraySizeException if any of the components in * the specified `dimensions` argument is negative. */ static newInstance(componentType: Class, ...dimensions: number[]): any; /** * Returns the length of the specified array object, as an `int`. * * @param array the array * @return the length of the array * @throws IllegalArgumentException if the object argument is not * an array */ static getLength(array: any): number; /** * Returns the value of the indexed component in the specified * array object. The value is automatically wrapped in an object * if it has a primitive type. * * @param array the array * @param index the index * @return the (possibly wrapped) value of the indexed component in * the specified array * @throws NullPointerException If the specified object is null * @throws IllegalArgumentException If the specified object is not * an array * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to the * length of the specified array */ static get(array: any, index: number): any; /** * Returns the value of the indexed component in the specified * array object, as a `boolean`. * * @param array the array * @param index the index * @return the value of the indexed component in the specified array * @throws NullPointerException If the specified object is null * @throws IllegalArgumentException If the specified object is not * an array, or if the indexed element cannot be converted to the * return type by an identity or widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to the * length of the specified array * @see Array#get */ static getBoolean(array: any, index: number): boolean; /** * Returns the value of the indexed component in the specified * array object, as a `byte`. * * @param array the array * @param index the index * @return the value of the indexed component in the specified array * @throws NullPointerException If the specified object is null * @throws IllegalArgumentException If the specified object is not * an array, or if the indexed element cannot be converted to the * return type by an identity or widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to the * length of the specified array * @see Array#get */ static getByte(array: any, index: number): number; /** * Returns the value of the indexed component in the specified * array object, as a `char`. * * @param array the array * @param index the index * @return the value of the indexed component in the specified array * @throws NullPointerException If the specified object is null * @throws IllegalArgumentException If the specified object is not * an array, or if the indexed element cannot be converted to the * return type by an identity or widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to the * length of the specified array * @see Array#get */ static getChar(array: any, index: number): string; /** * Returns the value of the indexed component in the specified * array object, as a `short`. * * @param array the array * @param index the index * @return the value of the indexed component in the specified array * @throws NullPointerException If the specified object is null * @throws IllegalArgumentException If the specified object is not * an array, or if the indexed element cannot be converted to the * return type by an identity or widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to the * length of the specified array * @see Array#get */ static getShort(array: any, index: number): number; /** * Returns the value of the indexed component in the specified * array object, as an `int`. * * @param array the array * @param index the index * @return the value of the indexed component in the specified array * @throws NullPointerException If the specified object is null * @throws IllegalArgumentException If the specified object is not * an array, or if the indexed element cannot be converted to the * return type by an identity or widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to the * length of the specified array * @see Array#get */ static getInt(array: any, index: number): number; /** * Returns the value of the indexed component in the specified * array object, as a `long`. * * @param array the array * @param index the index * @return the value of the indexed component in the specified array * @throws NullPointerException If the specified object is null * @throws IllegalArgumentException If the specified object is not * an array, or if the indexed element cannot be converted to the * return type by an identity or widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to the * length of the specified array * @see Array#get */ static getLong(array: any, index: number): number; /** * Returns the value of the indexed component in the specified * array object, as a `float`. * * @param array the array * @param index the index * @return the value of the indexed component in the specified array * @throws NullPointerException If the specified object is null * @throws IllegalArgumentException If the specified object is not * an array, or if the indexed element cannot be converted to the * return type by an identity or widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to the * length of the specified array * @see Array#get */ static getFloat(array: any, index: number): number; /** * Returns the value of the indexed component in the specified * array object, as a `double`. * * @param array the array * @param index the index * @return the value of the indexed component in the specified array * @throws NullPointerException If the specified object is null * @throws IllegalArgumentException If the specified object is not * an array, or if the indexed element cannot be converted to the * return type by an identity or widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to the * length of the specified array * @see Array#get */ static getDouble(array: any, index: number): number; /** * Sets the value of the indexed component of the specified array * object to the specified new value. The new value is first * automatically unwrapped if the array has a primitive component * type. * @param array the array * @param index the index into the array * @param value the new value of the indexed component * @throws NullPointerException If the specified object argument * is null * @throws IllegalArgumentException If the specified object argument * is not an array, or if the array component type is primitive and * an unwrapping conversion fails * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to * the length of the specified array */ static set(array: any, index: number, value: any): void; /** * Sets the value of the indexed component of the specified array * object to the specified `boolean` value. * @param array the array * @param index the index into the array * @param z the new value of the indexed component * @throws NullPointerException If the specified object argument * is null * @throws IllegalArgumentException If the specified object argument * is not an array, or if the specified value cannot be converted * to the underlying array's component type by an identity or a * primitive widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to * the length of the specified array * @see Array#set */ static setBoolean(array: any, index: number, z: boolean): void; /** * Sets the value of the indexed component of the specified array * object to the specified `byte` value. * @param array the array * @param index the index into the array * @param b the new value of the indexed component * @throws NullPointerException If the specified object argument * is null * @throws IllegalArgumentException If the specified object argument * is not an array, or if the specified value cannot be converted * to the underlying array's component type by an identity or a * primitive widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to * the length of the specified array * @see Array#set */ static setByte(array: any, index: number, b: number): void; /** * Sets the value of the indexed component of the specified array * object to the specified `char` value. * @param array the array * @param index the index into the array * @param c the new value of the indexed component * @throws NullPointerException If the specified object argument * is null * @throws IllegalArgumentException If the specified object argument * is not an array, or if the specified value cannot be converted * to the underlying array's component type by an identity or a * primitive widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to * the length of the specified array * @see Array#set */ static setChar(array: any, index: number, c: string): void; /** * Sets the value of the indexed component of the specified array * object to the specified `short` value. * @param array the array * @param index the index into the array * @param s the new value of the indexed component * @throws NullPointerException If the specified object argument * is null * @throws IllegalArgumentException If the specified object argument * is not an array, or if the specified value cannot be converted * to the underlying array's component type by an identity or a * primitive widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to * the length of the specified array * @see Array#set */ static setShort(array: any, index: number, s: number): void; /** * Sets the value of the indexed component of the specified array * object to the specified `int` value. * @param array the array * @param index the index into the array * @param i the new value of the indexed component * @throws NullPointerException If the specified object argument * is null * @throws IllegalArgumentException If the specified object argument * is not an array, or if the specified value cannot be converted * to the underlying array's component type by an identity or a * primitive widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to * the length of the specified array * @see Array#set */ static setInt(array: any, index: number, i: number): void; /** * Sets the value of the indexed component of the specified array * object to the specified `long` value. * @param array the array * @param index the index into the array * @param l the new value of the indexed component * @throws NullPointerException If the specified object argument * is null * @throws IllegalArgumentException If the specified object argument * is not an array, or if the specified value cannot be converted * to the underlying array's component type by an identity or a * primitive widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to * the length of the specified array * @see Array#set */ static setLong(array: any, index: number, l: number): void; /** * Sets the value of the indexed component of the specified array * object to the specified `float` value. * @param array the array * @param index the index into the array * @param f the new value of the indexed component * @throws NullPointerException If the specified object argument * is null * @throws IllegalArgumentException If the specified object argument * is not an array, or if the specified value cannot be converted * to the underlying array's component type by an identity or a * primitive widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to * the length of the specified array * @see Array#set */ static setFloat(array: any, index: number, f: number): void; /** * Sets the value of the indexed component of the specified array * object to the specified `double` value. * @param array the array * @param index the index into the array * @param d the new value of the indexed component * @throws NullPointerException If the specified object argument * is null * @throws IllegalArgumentException If the specified object argument * is not an array, or if the specified value cannot be converted * to the underlying array's component type by an identity or a * primitive widening conversion * @throws ArrayIndexOutOfBoundsException If the specified `index` * argument is negative, or if it is greater than or equal to * the length of the specified array * @see Array#set */ static setDouble(array: any, index: number, d: number): void; } /** * A `Method` provides information about, and access to, a single method * on a class or interface. The reflected method may be a class method * or an instance method (including an abstract method). * * A `Method` permits widening conversions to occur when matching the * actual parameters to invoke with the underlying method's formal * parameters, but it throws an `IllegalArgumentException` if a * narrowing conversion would occur. * * @see Member * @see java.lang.Class * @see java.lang.Class#getMethods() * @see java.lang.Class#getMethod(String, Class[]) * @see java.lang.Class#getDeclaredMethods() * @see java.lang.Class#getDeclaredMethod(String, Class[]) * * @author Kenneth Russell * @author Nakul Saraiya * @since 1.1 */ export class Method extends Executable { /** * @throws InaccessibleObjectException {@inheritDoc} * @throws SecurityException {@inheritDoc} */ setAccessible(flag: boolean): void; /** * Returns the `Class` object representing the class or interface * that declares the method represented by this object. */ get declaringClass(): Class; /** * Returns the name of the method represented by this `Method` * object, as a `String`. */ get name(): string; /** * {@inheritDoc} */ get modifiers(): number; /** * {@inheritDoc} * @throws GenericSignatureFormatError {@inheritDoc} * @since 1.5 */ get typeParameters(): TypeVariable[]; /** * Returns a `Class` object that represents the formal return type * of the method represented by this `Method` object. * * @return the return type for the method this object represents */ get returnType(): Class; /** * Returns a `Type` object that represents the formal return * type of the method represented by this `Method` object. * * If the return type is a parameterized type, * the `Type` object returned must accurately reflect * the actual type arguments used in the source code. * * If the return type is a type variable or a parameterized type, it * is created. Otherwise, it is resolved. * * @return a `Type` object that represents the formal return * type of the underlying method * @throws GenericSignatureFormatError * if the generic method signature does not conform to the format * specified in * The Java Virtual Machine Specification * @throws TypeNotPresentException if the underlying method's * return type refers to a non-existent class or interface declaration * @throws MalformedParameterizedTypeException if the * underlying method's return type refers to a parameterized * type that cannot be instantiated for any reason * @since 1.5 */ get genericReturnType(): Type; /** * {@inheritDoc} */ get parameterTypes(): Class[]; /** * {@inheritDoc} * @since 1.8 */ get parameterCount(): number; /** * {@inheritDoc} * @throws GenericSignatureFormatError {@inheritDoc} * @throws TypeNotPresentException {@inheritDoc} * @throws MalformedParameterizedTypeException {@inheritDoc} * @since 1.5 */ get genericParameterTypes(): Type[]; /** * {@inheritDoc} */ get exceptionTypes(): Class[]; /** * {@inheritDoc} * @throws GenericSignatureFormatError {@inheritDoc} * @throws TypeNotPresentException {@inheritDoc} * @throws MalformedParameterizedTypeException {@inheritDoc} * @since 1.5 */ get genericExceptionTypes(): Type[]; /** * Compares this `Method` against the specified object. Returns * true if the objects are the same. Two `Methods` are the same if * they were declared by the same class and have the same name * and formal parameter types and return type. */ equals(obj: any): boolean; /** * Returns a hashcode for this `Method`. The hashcode is computed * as the exclusive-or of the hashcodes for the underlying * method's declaring class name and the method's name. */ hashCode(): number; /** * Returns a string describing this `Method`. The string is * formatted as the method access modifiers, if any, followed by * the method return type, followed by a space, followed by the * class declaring the method, followed by a period, followed by * the method name, followed by a parenthesized, comma-separated * list of the method's formal parameter types. If the method * throws checked exceptions, the parameter list is followed by a * space, followed by the word "`throws`" followed by a * comma-separated list of the thrown exception types. * For example: * * public boolean java.lang.Object.equals(java.lang.Object) * * * The access modifiers are placed in canonical order as * specified by "The Java Language Specification". This is * `public`, `protected` or `private` first, * and then other modifiers in the following order: * `abstract`, `default`, `static`, `final`, * `synchronized`, `native`, `strictfp`. * * @return a string describing this `Method` * * @jls 8.4.3 Method Modifiers * @jls 9.4 Method Declarations * @jls 9.6.1 Annotation Interface Elements */ toString(): string; /** * Returns a string describing this `Method`, including type * parameters. The string is formatted as the method access * modifiers, if any, followed by an angle-bracketed * comma-separated list of the method's type parameters, if any, * including informative bounds of the type parameters, if any, * followed by the method's generic return type, followed by a * space, followed by the class declaring the method, followed by * a period, followed by the method name, followed by a * parenthesized, comma-separated list of the method's generic * formal parameter types. * * If this method was declared to take a variable number of * arguments, instead of denoting the last parameter as * "Type[]", it is denoted as * "Type...". * * A space is used to separate access modifiers from one another * and from the type parameters or return type. If there are no * type parameters, the type parameter list is elided; if the type * parameter list is present, a space separates the list from the * class name. If the method is declared to throw exceptions, the * parameter list is followed by a space, followed by the word * "`throws`" followed by a comma-separated list of the generic * thrown exception types. * * The access modifiers are placed in canonical order as * specified by "The Java Language Specification". This is * `public`, `protected` or `private` first, * and then other modifiers in the following order: * `abstract`, `default`, `static`, `final`, * `synchronized`, `native`, `strictfp`. * * @return a string describing this `Method`, * include type parameters * * @since 1.5 * * @jls 8.4.3 Method Modifiers * @jls 9.4 Method Declarations * @jls 9.6.1 Annotation Interface Elements */ toGenericString(): string; /** * Invokes the underlying method represented by this `Method` * object, on the specified object with the specified parameters. * Individual parameters are automatically unwrapped to match * primitive formal parameters, and both primitive and reference * parameters are subject to method invocation conversions as * necessary. * * If the underlying method is static, then the specified `obj` * argument is ignored. It may be null. * * If the number of formal parameters required by the underlying method is * 0, the supplied `args` array may be of length 0 or null. * * If the underlying method is an instance method, it is invoked * using dynamic method lookup as documented in The Java Language * Specification, section {@jls 15.12.4.4}; in particular, * overriding based on the runtime type of the target object may occur. * * If the underlying method is static, the class that declared * the method is initialized if it has not already been initialized. * * If the method completes normally, the value it returns is * returned to the caller of invoke; if the value has a primitive * type, it is first appropriately wrapped in an object. However, * if the value has the type of an array of a primitive type, the * elements of the array are not wrapped in objects; in * other words, an array of primitive type is returned. If the * underlying method return type is void, the invocation returns * null. * * @param obj the object the underlying method is invoked from * @param args the arguments used for the method call * @return the result of dispatching the method represented by * this object on `obj` with parameters * `args` * * @throws IllegalAccessException if this `Method` object * is enforcing Java language access control and the underlying * method is inaccessible. * @throws IllegalArgumentException if the method is an * instance method and the specified object argument * is not an instance of the class or interface * declaring the underlying method (or of a subclass * or implementor thereof); if the number of actual * and formal parameters differ; if an unwrapping * conversion for primitive arguments fails; or if, * after possible unwrapping, a parameter value * cannot be converted to the corresponding formal * parameter type by a method invocation conversion. * @throws InvocationTargetException if the underlying method * throws an exception. * @throws NullPointerException if the specified object is null * and the method is an instance method. * @throws ExceptionInInitializerError if the initialization * provoked by this method fails. */ invoke(obj: any, ...args: any[]): any; /** * Returns `true` if this method is a bridge * method; returns `false` otherwise. * * @return true if and only if this method is a bridge * method as defined by the Java Language Specification. * @since 1.5 */ isBridge(): boolean; /** * {@inheritDoc} * @since 1.5 */ isVarArgs(): boolean; /** * {@inheritDoc} * @jls 13.1 The Form of a Binary * @since 1.5 */ isSynthetic(): boolean; /** * Returns `true` if this method is a default * method; returns `false` otherwise. * * A default method is a public non-abstract instance method, that * is, a non-static method with a body, declared in an interface. * * @return true if and only if this method is a default * method as defined by the Java Language Specification. * @since 1.8 */ isDefault(): boolean; /** * Returns the default value for the annotation member represented by * this `Method` instance. If the member is of a primitive type, * an instance of the corresponding wrapper type is returned. Returns * null if no default is associated with the member, or if the method * instance does not represent a declared member of an annotation type. * * @return the default value for the annotation member represented * by this `Method` instance. * @throws TypeNotPresentException if the annotation is of type * {@link Class} and no definition can be found for the * default class value. * @since 1.5 */ get defaultValue(): any; /** * {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @since 1.5 */ getAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * @since 1.5 */ get declaredAnnotations(): Annotation[]; /** * {@inheritDoc} * @since 1.5 */ get parameterAnnotations(): Annotation[][]; /** * {@inheritDoc} * @since 1.8 */ get annotatedReturnType(): AnnotatedType; /** * Convenience method to set the `accessible` flag for an * array of reflected objects with a single security check (for efficiency). * * This method may be used to enable access to all reflected objects in * the array when access to each reflected object can be enabled as * specified by {@link #setAccessible(boolean) setAccessible(boolean)}. * * If there is a security manager, its * `checkPermission` method is first called with a * `ReflectPermission("suppressAccessChecks")` permission. * * A `SecurityException` is also thrown if any of the elements of * the input `array` is a {@link java.lang.reflect.Constructor} * object for the class `java.lang.Class` and `flag` is true. * * @param array the array of AccessibleObjects * @param flag the new value for the `accessible` flag * in each object * @throws InaccessibleObjectException if access cannot be enabled for all * objects in the array * @throws SecurityException if the request is denied by the security manager * or an element in the array is a constructor for ` * java.lang.Class` * @see SecurityManager#checkPermission * @see ReflectPermission * @revised 9 */ static setAccessible(array: AccessibleObject[], flag: boolean): void; /** * {@inheritDoc} * * Note that any annotations returned by this method are * declaration annotations. * * @since 1.5 */ get annotations(): Annotation[]; } export class InaccessibleObjectException extends RuntimeException { /** * Constructs an `InaccessibleObjectException` with no detail message. */ constructor(); /** * Constructs an `InaccessibleObjectException` with the given detail * message. * * @param msg * The detail message */ constructor(msg: string); } /** * A common interface for all entities that declare type variables. * * @since 1.5 */ export class GenericDeclaration extends AnnotatedElement { /** * Returns an array of `TypeVariable` objects that * represent the type variables declared by the generic * declaration represented by this `GenericDeclaration` * object, in declaration order. Returns an array of length 0 if * the underlying generic declaration declares no type variables. * * @return an array of `TypeVariable` objects that represent * the type variables declared by this generic declaration * @throws GenericSignatureFormatError if the generic * signature of this generic declaration does not conform to * the format specified in * The Java Virtual Machine Specification */ get typeParameters(): TypeVariable[]; } /** * Thrown by a method invocation on a proxy instance if its invocation * handler's {@link InvocationHandler#invoke invoke} method throws a * checked exception (a `Throwable` that is not assignable * to `RuntimeException` or `Error`) that * is not assignable to any of the exception types declared in the * `throws` clause of the method that was invoked on the * proxy instance and dispatched to the invocation handler. * * An `UndeclaredThrowableException` instance contains * the undeclared checked exception that was thrown by the invocation * handler, and it can be retrieved with the * `getUndeclaredThrowable()` method. * `UndeclaredThrowableException` extends * `RuntimeException`, so it is an unchecked exception * that wraps a checked exception. * * As of release 1.4, this exception has been retrofitted to * conform to the general purpose exception-chaining mechanism. The * "undeclared checked exception that was thrown by the invocation * handler" that may be provided at construction time and accessed via * the {@link #getUndeclaredThrowable()} method is now known as the * cause, and may be accessed via the {@link * Throwable#getCause()} method, as well as the aforementioned "legacy * method." * * @author Peter Jones * @see InvocationHandler * @since 1.3 */ export class UndeclaredThrowableException extends RuntimeException { /** * Constructs an `UndeclaredThrowableException` with the * specified `Throwable`. * * @param undeclaredThrowable the undeclared checked exception * that was thrown */ constructor(undeclaredThrowable: Throwable); /** * Constructs an `UndeclaredThrowableException` with the * specified `Throwable` and a detail message. * * @param undeclaredThrowable the undeclared checked exception * that was thrown * @param s the detail message */ constructor(undeclaredThrowable: Throwable, s: string); /** * Returns the `Throwable` instance wrapped in this * `UndeclaredThrowableException`, which may be `null`. * * This method predates the general-purpose exception chaining facility. * The {@link Throwable#getCause()} method is now the preferred means of * obtaining this information. * * @return the undeclared checked exception that was thrown */ get undeclaredThrowable(): Throwable; } /** * `GenericArrayType` represents an array type whose component * type is either a parameterized type or a type variable. * * @jls 10.1 Array Types * @since 1.5 */ export class GenericArrayType extends Type { /** * Returns a `Type` object representing the component type * of this array. This method creates the component type of the * array. See the declaration of {@link * java.lang.reflect.ParameterizedType ParameterizedType} for the * semantics of the creation process for parameterized types and * see {@link java.lang.reflect.TypeVariable TypeVariable} for the * creation process for type variables. * * @return a `Type` object representing the component type * of this array * @throws TypeNotPresentException if the underlying array type's component * type refers to a non-existent class or interface declaration * @throws MalformedParameterizedTypeException if the * underlying array type's component type refers to a * parameterized type that cannot be instantiated for any reason */ get genericComponentType(): Type; } /** * `AnnotatedType` represents the potentially annotated use of a type in * the program currently running in this VM. The use may be of any type in the * Java programming language, including an array type, a parameterized type, a * type variable, or a wildcard type. * * Note that any annotations returned by methods on this interface are * type annotations (JLS {@jls 9.7.4}) as the entity being * potentially annotated is a type. * * @jls 4.1 The Kinds of Types and Values * @jls 4.2 Primitive Types and Values * @jls 4.3 Reference Types and Values * @jls 4.4 Type Variables * @jls 4.5 Parameterized Types * @jls 4.8 Raw Types * @jls 4.9 Intersection Types * @jls 10.1 Array Types * @since 1.8 */ export class AnnotatedType extends AnnotatedElement { /** * Returns the potentially annotated type that this type is a member of, if * this type represents a nested type. For example, if this type is * `@TA O.I`, return a representation of `@TA O`. * * Returns `null` if this `AnnotatedType` represents a * top-level class or interface, or a local or anonymous class, or * a primitive type, or void. * * Returns `null` if this `AnnotatedType` is an instance of * `AnnotatedArrayType`, `AnnotatedTypeVariable`, or * `AnnotatedWildcardType`. * * @implSpec * This default implementation returns `null` and performs no other * action. * * @return an `AnnotatedType` object representing the potentially * annotated type that this type is a member of, or `null` * @throws TypeNotPresentException if the owner type * refers to a non-existent class or interface declaration * @throws MalformedParameterizedTypeException if the owner type * refers to a parameterized type that cannot be instantiated * for any reason * * @since 9 */ get annotatedOwnerType(): AnnotatedType; /** * Returns the underlying type that this annotated type represents. * * @return the type this annotated type represents */ get type(): Type; /** * {@inheritDoc} * Note that any annotation returned by this method is a type * annotation. * * @throws NullPointerException {@inheritDoc} */ getAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * Note that any annotations returned by this method are type * annotations. */ get annotations(): Annotation[]; /** * {@inheritDoc} * Note that any annotations returned by this method are type * annotations. */ get declaredAnnotations(): Annotation[]; } /** * A `RecordComponent` provides information about, and dynamic access to, a * component of a record class. * * @see Class#getRecordComponents() * @see java.lang.Record * @jls 8.10 Record Classes * @since 16 */ export class RecordComponent extends AnnotatedElement { /** * Returns the name of this record component. * * @return the name of this record component */ get name(): string; /** * Returns a `Class` that identifies the declared type for this * record component. * * @return a `Class` identifying the declared type of the component * represented by this record component */ get type(): Class; /** * Returns a `String` that describes the generic type signature for * this record component. * * @return a `String` that describes the generic type signature for * this record component * * @jvms 4.7.9.1 Signatures */ get genericSignature(): string; /** * Returns a `Type` object that represents the declared type for * this record component. * * If the declared type of the record component is a parameterized type, * the `Type` object returned reflects the actual type arguments used * in the source code. * * If the type of the underlying record component is a type variable or a * parameterized type, it is created. Otherwise, it is resolved. * * @return a `Type` object that represents the declared type for * this record component * @throws GenericSignatureFormatError if the generic record component * signature does not conform to the format specified in * The Java Virtual Machine Specification * @throws TypeNotPresentException if the generic type * signature of the underlying record component refers to a non-existent * type declaration * @throws MalformedParameterizedTypeException if the generic * signature of the underlying record component refers to a parameterized * type that cannot be instantiated for any reason */ get genericType(): Type; /** * Returns an `AnnotatedType` object that represents the use of a type to specify * the declared type of this record component. * * @return an object representing the declared type of this record component */ get annotatedType(): AnnotatedType; /** * Returns a `Method` that represents the accessor for this record * component. * * @return a `Method` that represents the accessor for this record * component */ get accessor(): Method; /** * {@inheritDoc} * Note that any annotation returned by this method is a * declaration annotation. * @throws NullPointerException {@inheritDoc} */ getAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. */ get annotations(): Annotation[]; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. */ get declaredAnnotations(): Annotation[]; /** * Returns a string describing this record component. The format is * the record component type, followed by a space, followed by the name * of the record component. * For example: * * java.lang.String name * int age * * * @return a string describing this record component */ toString(): string; /** * Returns the record class which declares this record component. * * @return The record class declaring this record component. */ get declaringRecord(): Class; } /** * Represents an annotated construct of the program currently running * in this VM. * * A construct is either an element or a type. Annotations on an * element are on a declaration, whereas annotations on a * type are on a specific use of a type name. * * As defined by The Java Language Specification * section {@jls 9.7.4}, an annotation on an element is a * declaration annotation and an annotation on a type is a * type annotation. * * Note that any annotations returned by methods on the {@link * AnnotatedType AnnotatedType} interface and its subinterfaces are * type annotations as the entity being potentially annotated is a * type. Annotations returned by methods outside of the ` * AnnotatedType` hierarchy are declaration annotations. * * This interface allows annotations to be read reflectively. All * annotations returned by methods in this interface are immutable and * serializable. The arrays returned by methods of this interface may * be modified by callers without affecting the arrays returned to * other callers. * * The {@link #getAnnotationsByType(Class)} and {@link * #getDeclaredAnnotationsByType(Class)} methods support multiple * annotations of the same type on an element. If the argument to * either method is a repeatable annotation type (JLS {@jls 9.6}), * then the method will "look through" a container annotation (JLS * {@jls 9.7}), if present, and return any annotations inside the * container. Container annotations may be generated at compile-time * to wrap multiple annotations of the argument type. * * The terms directly present, indirectly present, * present, and associated are used throughout this * interface to describe precisely which annotations are returned by * methods: * * * * An annotation A is directly present on an * element E if E has a ` * RuntimeVisibleAnnotations` or ` * RuntimeVisibleParameterAnnotations` or ` * RuntimeVisibleTypeAnnotations` attribute, and the attribute * contains A. * * An annotation A is indirectly present on an * element E if E has a `RuntimeVisibleAnnotations` or * `RuntimeVisibleParameterAnnotations` or `RuntimeVisibleTypeAnnotations` * attribute, and A 's type is repeatable, and the attribute contains * exactly one annotation whose value element contains A and whose * type is the containing annotation type of A 's type. * * An annotation A is present on an element E if either: * * * * A is directly present on E; or * * No annotation of A 's type is directly present on * E, and E is a class, and A 's type is * inheritable, and A is present on the superclass of E. * * * * An annotation A is associated with an element E * if either: * * * * A is directly or indirectly present on E; or * * No annotation of A 's type is directly or indirectly * present on E, and E is a class, and A's type * is inheritable, and A is associated with the superclass of * E. * * * * * * The table below summarizes which kind of annotation presence * different methods in this interface examine. * * * Overview of kind of presence detected by different AnnotatedElement methods * * Method * Kind of Presence * Return Type * Signature * Directly Present * Indirectly Present * Present * Associated * * * `T` * {@link #getAnnotation(Class) getAnnotation(Class)} * X * * `Annotation[]` * {@link #getAnnotations getAnnotations()} * X * * `T[]` * {@link #getAnnotationsByType(Class) getAnnotationsByType(Class)} * X * * `T` * {@link #getDeclaredAnnotation(Class) getDeclaredAnnotation(Class)} * X * * `Annotation[]` * {@link #getDeclaredAnnotations getDeclaredAnnotations()} * X * * `T[]` * {@link #getDeclaredAnnotationsByType(Class) getDeclaredAnnotationsByType(Class)} * XX * * * * * For an invocation of `get[Declared]AnnotationsByType(Class )`, * the order of annotations which are directly or indirectly * present on an element E is computed as if indirectly present * annotations on E are directly present on E in place * of their container annotation, in the order in which they appear in * the value element of the container annotation. * * There are several compatibility concerns to keep in mind if an * annotation type T is originally not repeatable and * later modified to be repeatable. * * The containing annotation type for T is TC. * * * * Modifying T to be repeatable is source and binary * compatible with existing uses of T and with existing uses * of TC. * * That is, for source compatibility, source code with annotations of * type T or of type TC will still compile. For binary * compatibility, class files with annotations of type T or of * type TC (or with other kinds of uses of type T or of * type TC) will link against the modified version of T * if they linked against the earlier version. * * (An annotation type TC may informally serve as an acting * containing annotation type before T is modified to be * formally repeatable. Alternatively, when T is made * repeatable, TC can be introduced as a new type.) * * If an annotation type TC is present on an element, and * T is modified to be repeatable with TC as its * containing annotation type then: * * * * The change to T is behaviorally compatible with respect * to the `get[Declared]Annotation(Class)` (called with an * argument of T or TC) and ` * get[Declared]Annotations()` methods because the results of the * methods will not change due to TC becoming the containing * annotation type for T. * * The change to T changes the results of the ` * get[Declared]AnnotationsByType(Class)` methods called with an * argument of T, because those methods will now recognize an * annotation of type TC as a container annotation for T * and will "look through" it to expose annotations of type T. * * * * If an annotation of type T is present on an * element and T is made repeatable and more annotations of * type T are added to the element: * * * * The addition of the annotations of type T is both * source compatible and binary compatible. * * The addition of the annotations of type T changes the results * of the `get[Declared]Annotation(Class)` methods and ` * get[Declared]Annotations()` methods, because those methods will now * only see a container annotation on the element and not see an * annotation of type T. * * The addition of the annotations of type T changes the * results of the `get[Declared]AnnotationsByType(Class)` * methods, because their results will expose the additional * annotations of type T whereas previously they exposed only a * single annotation of type T. * * * * * * If an annotation returned by a method in this interface contains * (directly or indirectly) a {@link Class}-valued member referring to * a class that is not accessible in this VM, attempting to read the class * by calling the relevant Class-returning method on the returned annotation * will result in a {@link TypeNotPresentException}. * * Similarly, attempting to read an enum-valued member will result in * a {@link EnumConstantNotPresentException} if the enum constant in the * annotation is no longer present in the enum class. * * If an annotation type T is (meta-)annotated with an * `@Repeatable` annotation whose value element indicates a type * TC, but TC does not declare a `value()` method * with a return type of T`[]`, then an exception of type * {@link java.lang.annotation.AnnotationFormatError} is thrown. * * Finally, attempting to read a member whose definition has evolved * incompatibly will result in a {@link * java.lang.annotation.AnnotationTypeMismatchException} or an * {@link java.lang.annotation.IncompleteAnnotationException}. * * @see java.lang.EnumConstantNotPresentException * @see java.lang.TypeNotPresentException * @see AnnotationFormatError * @see java.lang.annotation.AnnotationTypeMismatchException * @see java.lang.annotation.IncompleteAnnotationException * @since 1.5 * @author Josh Bloch */ export class AnnotatedElement { /** * Returns true if an annotation for the specified type * is present on this element, else false. This method * is designed primarily for convenient access to marker annotations. * * The truth value returned by this method is equivalent to: * `getAnnotation(annotationClass) != null` * * @implSpec The default implementation returns ` * getAnnotation(annotationClass) != null`. * * @param annotationClass the Class object corresponding to the * annotation type * @return true if an annotation for the specified annotation * type is present on this element, else false * @throws NullPointerException if the given annotation class is null * @since 1.5 */ isAnnotationPresent(annotationClass: Class): boolean; /** * Returns this element's annotation for the specified type if * such an annotation is present, else null. * * @param the type of the annotation to query for and return if present * @param annotationClass the Class object corresponding to the * annotation type * @return this element's annotation for the specified annotation type if * present on this element, else null * @throws NullPointerException if the given annotation class is null * @since 1.5 */ getAnnotation(annotationClass: Class): T; /** * Returns annotations that are present on this element. * * If there are no annotations present on this element, the return * value is an array of length 0. * * The caller of this method is free to modify the returned array; it will * have no effect on the arrays returned to other callers. * * @return annotations present on this element * @since 1.5 */ get annotations(): Annotation[]; /** * Returns annotations that are associated with this element. * * If there are no annotations associated with this element, the return * value is an array of length 0. * * The difference between this method and {@link #getAnnotation(Class)} * is that this method detects if its argument is a repeatable * annotation type (JLS {@jls 9.6}), and if so, attempts to find one or * more annotations of that type by "looking through" a container * annotation. * * The caller of this method is free to modify the returned array; it will * have no effect on the arrays returned to other callers. * * @implSpec The default implementation first calls {@link * #getDeclaredAnnotationsByType(Class)} passing ` * annotationClass` as the argument. If the returned array has * length greater than zero, the array is returned. If the returned * array is zero-length and this `AnnotatedElement` is a * class and the argument type is an inheritable annotation type, * and the superclass of this `AnnotatedElement` is non-null, * then the returned result is the result of calling {@link * #getAnnotationsByType(Class)} on the superclass with ` * annotationClass` as the argument. Otherwise, a zero-length * array is returned. * * @param the type of the annotation to query for and return if present * @param annotationClass the Class object corresponding to the * annotation type * @return all this element's annotations for the specified annotation type if * associated with this element, else an array of length zero * @throws NullPointerException if the given annotation class is null * @since 1.8 */ getAnnotationsByType(annotationClass: Class): T[]; /** * Returns this element's annotation for the specified type if * such an annotation is directly present, else null. * * This method ignores inherited annotations. (Returns null if no * annotations are directly present on this element.) * * @implSpec The default implementation first performs a null check * and then loops over the results of {@link * #getDeclaredAnnotations} returning the first annotation whose * annotation type matches the argument type. * * @param the type of the annotation to query for and return if directly present * @param annotationClass the Class object corresponding to the * annotation type * @return this element's annotation for the specified annotation type if * directly present on this element, else null * @throws NullPointerException if the given annotation class is null * @since 1.8 */ getDeclaredAnnotation(annotationClass: Class): T; /** * Returns this element's annotation(s) for the specified type if * such annotations are either directly present or * indirectly present. This method ignores inherited * annotations. * * If there are no specified annotations directly or indirectly * present on this element, the return value is an array of length * 0. * * The difference between this method and {@link * #getDeclaredAnnotation(Class)} is that this method detects if its * argument is a repeatable annotation type (JLS {@jls 9.6}), and if so, * attempts to find one or more annotations of that type by "looking * through" a container annotation if one is present. * * The caller of this method is free to modify the returned array; it will * have no effect on the arrays returned to other callers. * * @implSpec The default implementation may call {@link * #getDeclaredAnnotation(Class)} one or more times to find a * directly present annotation and, if the annotation type is * repeatable, to find a container annotation. If annotations of * the annotation type `annotationClass` are found to be both * directly and indirectly present, then {@link * #getDeclaredAnnotations()} will get called to determine the * order of the elements in the returned array. * * Alternatively, the default implementation may call {@link * #getDeclaredAnnotations()} a single time and the returned array * examined for both directly and indirectly present * annotations. The results of calling {@link * #getDeclaredAnnotations()} are assumed to be consistent with the * results of calling {@link #getDeclaredAnnotation(Class)}. * * @param the type of the annotation to query for and return * if directly or indirectly present * @param annotationClass the Class object corresponding to the * annotation type * @return all this element's annotations for the specified annotation type if * directly or indirectly present on this element, else an array of length zero * @throws NullPointerException if the given annotation class is null * @since 1.8 */ getDeclaredAnnotationsByType(annotationClass: Class): T[]; /** * Returns annotations that are directly present on this element. * This method ignores inherited annotations. * * If there are no annotations directly present on this element, * the return value is an array of length 0. * * The caller of this method is free to modify the returned array; it will * have no effect on the arrays returned to other callers. * * @return annotations directly present on this element * @since 1.5 */ get declaredAnnotations(): Annotation[]; } /** * Information about method parameters. * * A `Parameter` provides information about method parameters, * including its name and modifiers. It also provides an alternate * means of obtaining attributes for the parameter. * * @since 1.8 */ export class Parameter extends AnnotatedElement { /** * Compares based on the executable and the index. * * @param obj The object to compare. * @return Whether or not this is equal to the argument. */ equals(obj: any): boolean; /** * Returns a hash code based on the executable's hash code and the * index. * * @return A hash code based on the executable's hash code. */ hashCode(): number; /** * Returns true if the parameter has a name according to the class * file; returns false otherwise. Whether a parameter has a name * is determined by the {@literal MethodParameters} attribute of * the method which declares the parameter. * * @return true if and only if the parameter has a name according * to the class file. */ isNamePresent(): boolean; /** * Returns a string describing this parameter. The format is the * modifiers for the parameter, if any, in canonical order as * recommended by The Java Language * Specification, followed by the fully-qualified type of * the parameter (excluding the last [] if the parameter is * variable arity), followed by "..." if the parameter is variable * arity, followed by a space, followed by the name of the * parameter. * * @return A string representation of the parameter and associated * information. */ toString(): string; /** * Return the `Executable` which declares this parameter. * * @return The `Executable` declaring this parameter. */ get declaringExecutable(): Executable; /** * Get the modifier flags for this the parameter represented by * this `Parameter` object. * * @return The modifier flags for this parameter. */ get modifiers(): number; /** * Returns the name of the parameter. If the parameter's name is * {@linkplain #isNamePresent() present}, then this method returns * the name provided by the class file. Otherwise, this method * synthesizes a name of the form argN, where N is the index of * the parameter in the descriptor of the method which declares * the parameter. * * @return The name of the parameter, either provided by the class * file or synthesized if the class file does not provide * a name. */ get name(): string; /** * Returns a `Type` object that identifies the parameterized * type for the parameter represented by this `Parameter` * object. * * @return a `Type` object identifying the parameterized * type of the parameter represented by this object */ get parameterizedType(): Type; /** * Returns a `Class` object that identifies the * declared type for the parameter represented by this * `Parameter` object. * * @return a `Class` object identifying the declared * type of the parameter represented by this object */ get type(): Class; /** * Returns an AnnotatedType object that represents the use of a type to * specify the type of the formal parameter represented by this Parameter. * * @return an `AnnotatedType` object representing the use of a type * to specify the type of the formal parameter represented by this * Parameter */ get annotatedType(): AnnotatedType; /** * Returns `true` if this parameter is implicitly declared * in source code; returns `false` otherwise. * * @return true if and only if this parameter is implicitly * declared as defined by The Java Language * Specification. */ isImplicit(): boolean; /** * Returns `true` if this parameter is neither implicitly * nor explicitly declared in source code; returns `false` * otherwise. * * @jls 13.1 The Form of a Binary * @return true if and only if this parameter is a synthetic * construct as defined by * The Java Language Specification. */ isSynthetic(): boolean; /** * Returns `true` if this parameter represents a variable * argument list; returns `false` otherwise. * * @return `true` if an only if this parameter represents a * variable argument list. */ isVarArgs(): boolean; /** * {@inheritDoc} * Note that any annotation returned by this method is a * declaration annotation. * @throws NullPointerException {@inheritDoc} */ getAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. * * @throws NullPointerException {@inheritDoc} */ getAnnotationsByType(annotationClass: Class): T[]; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. */ get declaredAnnotations(): Annotation[]; /** * {@inheritDoc} * Note that any annotation returned by this method is a * declaration annotation. * * @throws NullPointerException {@inheritDoc} */ getDeclaredAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. * * @throws NullPointerException {@inheritDoc} */ getDeclaredAnnotationsByType(annotationClass: Class): T[]; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. */ get annotations(): Annotation[]; } /** * `InvocationHandler` is the interface implemented by * the invocation handler of a proxy instance. * * Each proxy instance has an associated invocation handler. * When a method is invoked on a proxy instance, the method * invocation is encoded and dispatched to the `invoke` * method of its invocation handler. * * @author Peter Jones * @see Proxy * @since 1.3 */ export class InvocationHandler { /** * Processes a method invocation on a proxy instance and returns * the result. This method will be invoked on an invocation handler * when a method is invoked on a proxy instance that it is * associated with. * * @param proxy the proxy instance that the method was invoked on * * @param method the `Method` instance corresponding to * the interface method invoked on the proxy instance. The declaring * class of the `Method` object will be the interface that * the method was declared in, which may be a superinterface of the * proxy interface that the proxy class inherits the method through. * * @param args an array of objects containing the values of the * arguments passed in the method invocation on the proxy instance, * or `null` if interface method takes no arguments. * Arguments of primitive types are wrapped in instances of the * appropriate primitive wrapper class, such as * `java.lang.Integer` or `java.lang.Boolean`. * * @return the value to return from the method invocation on the * proxy instance. If the declared return type of the interface * method is a primitive type, then the value returned by * this method must be an instance of the corresponding primitive * wrapper class; otherwise, it must be a type assignable to the * declared return type. If the value returned by this method is * `null` and the interface method's return type is * primitive, then a `NullPointerException` will be * thrown by the method invocation on the proxy instance. If the * value returned by this method is otherwise not compatible with * the interface method's declared return type as described above, * a `ClassCastException` will be thrown by the method * invocation on the proxy instance. * * @throws Throwable the exception to throw from the method * invocation on the proxy instance. The exception's type must be * assignable either to any of the exception types declared in the * `throws` clause of the interface method or to the * unchecked exception types `java.lang.RuntimeException` * or `java.lang.Error`. If a checked exception is * thrown by this method that is not assignable to any of the * exception types declared in the `throws` clause of * the interface method, then an * {@link UndeclaredThrowableException} containing the * exception that was thrown by this method will be thrown by the * method invocation on the proxy instance. * * @see UndeclaredThrowableException */ invoke(proxy: any, method: Method, args: any[]): any; /** * Invokes the specified default method on the given `proxy` instance with * the given parameters. The given `method` must be a default method * declared in a proxy interface of the `proxy`'s class or inherited * from its superinterface directly or indirectly. * * Invoking this method behaves as if `invokespecial` instruction executed * from the proxy class, targeting the default method in a proxy interface. * This is equivalent to the invocation: * `X.super.m(A* a)` where `X` is a proxy interface and the call to * `X.super::m(A*)` is resolved to the given `method`. * * Examples: interface `A` and `B` both declare a default * implementation of method `m`. Interface `C` extends `A` * and inherits the default method `m` from its superinterface `A`. * * {@code * interface A { * default T m(A a) { return t1; } * } * interface B { * default T m(A a) { return t2; } * } * interface C extends A {} * } * * The following creates a proxy instance that implements `A` * and invokes the default method `A::m`. * * ` * Object proxy = Proxy.newProxyInstance(loader, new Class[] { A.class `, * (o, m, params) -> { * if (m.isDefault()) { * // if it's a default method, invoke it * return InvocationHandler.invokeDefault(o, m, params); * } * }); * } * * If a proxy instance implements both `A` and `B`, both * of which provides the default implementation of method `m`, * the invocation handler can dispatch the method invocation to * `A::m` or `B::m` via the `invokeDefault` method. * For example, the following code delegates the method invocation * to `B::m`. * * ` * Object proxy = Proxy.newProxyInstance(loader, new Class[] { A.class, B.class `, * (o, m, params) -> { * if (m.getName().equals("m")) { * // invoke B::m instead of A::m * Method bMethod = B.class.getMethod(m.getName(), m.getParameterTypes()); * return InvocationHandler.invokeDefault(o, bMethod, params); * } * }); * } * * If a proxy instance implements `C` that inherits the default * method `m` from its superinterface `A`, then * the interface method invocation on `"m"` is dispatched to * the invocation handler's {@link #invoke(Object, Method, Object[]) invoke} * method with the `Method` object argument representing the * default method `A::m`. * * ` * Object proxy = Proxy.newProxyInstance(loader, new Class[] { C.class `, * (o, m, params) -> { * if (m.isDefault()) { * // behaves as if calling C.super.m(params) * return InvocationHandler.invokeDefault(o, m, params); * } * }); * } * * The invocation of method `"m"` on this `proxy` will behave * as if `C.super::m` is called and that is resolved to invoking * `A::m`. * * Adding a default method, or changing a method from abstract to default * may cause an exception if an existing code attempts to call `invokeDefault` * to invoke a default method. * * For example, if `C` is modified to implement a default method * `m`: * * {@code * interface C extends A { * default T m(A a) { return t3; } * } * } * * The code above that creates proxy instance `proxy` with * the modified `C` will run with no exception and it will result in * calling `C::m` instead of `A::m`. * * The following is another example that creates a proxy instance of `C` * and the invocation handler calls the `invokeDefault` method * to invoke `A::m`: * * ` * C c = (C) Proxy.newProxyInstance(loader, new Class[] { C.class `, * (o, m, params) -> { * if (m.getName().equals("m")) { * // IllegalArgumentException thrown as `A::m` is not a method * // inherited from its proxy interface C * Method aMethod = A.class.getMethod(m.getName(), m.getParameterTypes()); * return InvocationHandler.invokeDefault(o, aMethod params); * } * }); * c.m(...); * } * * The above code runs successfully with the old version of `C` and * `A::m` is invoked. When running with the new version of `C`, * the above code will fail with `IllegalArgumentException` because * `C` overrides the implementation of the same method and * `A::m` is not accessible by a proxy instance. * * @apiNote * The `proxy` parameter is of type `Object` rather than `Proxy` * to make it easy for {@link InvocationHandler#invoke(Object, Method, Object[]) * InvocationHandler::invoke} implementation to call directly without the need * of casting. * * @param proxy the `Proxy` instance on which the default method to be invoked * @param method the `Method` instance corresponding to a default method * declared in a proxy interface of the proxy class or inherited * from its superinterface directly or indirectly * @param args the parameters used for the method invocation; can be `null` * if the number of formal parameters required by the method is zero. * @return the value returned from the method invocation * * @throws IllegalArgumentException if any of the following conditions is `true`: * * `proxy` is not {@linkplain Proxy#isProxyClass(Class) * a proxy instance}; or * the given `method` is not a default method declared * in a proxy interface of the proxy class and not inherited from * any of its superinterfaces; or * the given `method` is overridden directly or indirectly by * the proxy interfaces and the method reference to the named * method never resolves to the given `method`; or * the length of the given `args` array does not match the * number of parameters of the method to be invoked; or * any of the `args` elements fails the unboxing * conversion if the corresponding method parameter type is * a primitive type; or if, after possible unboxing, any of the * `args` elements cannot be assigned to the corresponding * method parameter type. * * @throws IllegalAccessException if the declaring class of the specified * default method is inaccessible to the caller class * @throws NullPointerException if `proxy` or `method` is `null` * @throws Throwable anything thrown by the default method * @since 16 * @jvms 5.4.3. Method Resolution */ static invokeDefault(proxy: any, method: Method, ...args: any[]): any; } /** * `AnnotatedTypeVariable` represents the potentially annotated use of a * type variable, whose declaration may have bounds which themselves represent * annotated uses of types. * * @jls 4.4 Type Variables * @since 1.8 */ export class AnnotatedTypeVariable extends AnnotatedType { /** * Returns the potentially annotated bounds of this type variable. * If no bound is explicitly declared, the bound is unannotated * `Object`. * * @return the potentially annotated bounds of this type variable * @see TypeVariable#getBounds() */ get annotatedBounds(): AnnotatedType[]; /** * Returns the potentially annotated type that this type is a member of, if * this type represents a nested type. For example, if this type is * `@TA O.I`, return a representation of `@TA O`. * * Returns `null` for an `AnnotatedType` that is an instance * of `AnnotatedTypeVariable`. * * @return `null` * * @since 9 */ get annotatedOwnerType(): AnnotatedType; } /** * The `AccessibleObject` class is the base class for `Field`, * `Method`, and `Constructor` objects (known as reflected * objects). It provides the ability to flag a reflected object as * suppressing checks for Java language access control when it is used. This * permits sophisticated applications with sufficient privilege, such as Java * Object Serialization or other persistence mechanisms, to manipulate objects * in a manner that would normally be prohibited. * * Java language access control prevents use of private members outside * their top-level class; package access members outside their package; protected members * outside their package or subclasses; and public members outside their * module unless they are declared in an {@link Module#isExported(String,Module) * exported} package and the user {@link Module#canRead reads} their module. By * default, Java language access control is enforced (with one variation) when * `Field`s, `Method`s, or `Constructor`s are used to get or * set fields, to invoke methods, or to create and initialize new instances of * classes, respectively. Every reflected object checks that the code using it * is in an appropriate class, package, or module. The check when invoked by * JNI code with no Java * class on the stack only succeeds if the member and the declaring class are * public, and the class is in a package that is exported to all modules. * * The one variation from Java language access control is that the checks * by reflected objects assume readability. That is, the module containing * the use of a reflected object is assumed to read the module in which * the underlying field, method, or constructor is declared. * * Whether the checks for Java language access control can be suppressed * (and thus, whether access can be enabled) depends on whether the reflected * object corresponds to a member in an exported or open package * (see {@link #setAccessible(boolean)}). * * @jls 6.6 Access Control * @since 1.2 * @revised 9 */ export class AccessibleObject extends AnnotatedElement { /** * Convenience method to set the `accessible` flag for an * array of reflected objects with a single security check (for efficiency). * * This method may be used to enable access to all reflected objects in * the array when access to each reflected object can be enabled as * specified by {@link #setAccessible(boolean) setAccessible(boolean)}. * * If there is a security manager, its * `checkPermission` method is first called with a * `ReflectPermission("suppressAccessChecks")` permission. * * A `SecurityException` is also thrown if any of the elements of * the input `array` is a {@link java.lang.reflect.Constructor} * object for the class `java.lang.Class` and `flag` is true. * * @param array the array of AccessibleObjects * @param flag the new value for the `accessible` flag * in each object * @throws InaccessibleObjectException if access cannot be enabled for all * objects in the array * @throws SecurityException if the request is denied by the security manager * or an element in the array is a constructor for ` * java.lang.Class` * @see SecurityManager#checkPermission * @see ReflectPermission * @revised 9 */ static setAccessible(array: AccessibleObject[], flag: boolean): void; /** * Set the `accessible` flag for this reflected object to * the indicated boolean value. A value of `true` indicates that * the reflected object should suppress checks for Java language access * control when it is used. A value of `false` indicates that * the reflected object should enforce checks for Java language access * control when it is used, with the variation noted in the class description. * * This method may be used by a caller in class `C` to enable * access to a {@link Member member} of {@link Member#getDeclaringClass() * declaring class} `D` if any of the following hold: * * * `C` and `D` are in the same module. * * The member is `public` and `D` is `public` in * a package that the module containing `D` {@link * Module#isExported(String,Module) exports} to at least the module * containing `C`. * * The member is `protected` `static`, `D` is * `public` in a package that the module containing `D` * exports to at least the module containing `C`, and `C` * is a subclass of `D`. * * `D` is in a package that the module containing `D` * {@link Module#isOpen(String,Module) opens} to at least the module * containing `C`. * All packages in unnamed and open modules are open to all modules and * so this method always succeeds when `D` is in an unnamed or * open module. * * * This method cannot be used to enable access to private members, * members with default (package) access, protected instance members, or * protected constructors when the declaring class is in a different module * to the caller and the package containing the declaring class is not open * to the caller's module. * * This method cannot be used to enable {@linkplain Field#set write} * access to a non-modifiable final field. The following fields * are non-modifiable: * * static final fields declared in any class or interface * final fields declared in a {@linkplain Class#isHidden() hidden class} * final fields declared in a {@linkplain Class#isRecord() record} * * The `accessible` flag when `true` suppresses Java language access * control checks to only enable {@linkplain Field#get read} access to * these non-modifiable final fields. * * If there is a security manager, its * `checkPermission` method is first called with a * `ReflectPermission("suppressAccessChecks")` permission. * * @param flag the new value for the `accessible` flag * @throws InaccessibleObjectException if access cannot be enabled * @throws SecurityException if the request is denied by the security manager * @see #trySetAccessible * @see java.lang.invoke.MethodHandles#privateLookupIn * @revised 9 */ setAccessible(flag: boolean): void; /** * Set the `accessible` flag for this reflected object to `true` * if possible. This method sets the `accessible` flag, as if by * invoking {@link #setAccessible(boolean) setAccessible(true)}, and returns * the possibly-updated value for the `accessible` flag. If access * cannot be enabled, i.e. the checks or Java language access control cannot * be suppressed, this method returns `false` (as opposed to ` * setAccessible(true)` throwing `InaccessibleObjectException` when * it fails). * * This method is a no-op if the `accessible` flag for * this reflected object is `true`. * * For example, a caller can invoke `trySetAccessible` * on a `Method` object for a private instance method * `p.T::privateMethod` to suppress the checks for Java language access * control when the `Method` is invoked. * If `p.T` class is in a different module to the caller and * package `p` is open to at least the caller's module, * the code below successfully sets the `accessible` flag * to `true`. * * * {@code * p.T obj = ....; // instance of p.T * : * Method m = p.T.class.getDeclaredMethod("privateMethod"); * if (m.trySetAccessible()) { * m.invoke(obj); * } else { * // package p is not opened to the caller to access private member of T * ... * } * } * * If there is a security manager, its `checkPermission` method * is first called with a `ReflectPermission("suppressAccessChecks")` * permission. * * @return `true` if the `accessible` flag is set to `true`; * `false` if access cannot be enabled. * @throws SecurityException if the request is denied by the security manager * * @since 9 * @see java.lang.invoke.MethodHandles#privateLookupIn */ trySetAccessible(): boolean; /** * Get the value of the `accessible` flag for this reflected object. * * @return the value of the object's `accessible` flag * * @deprecated * This method is deprecated because its name hints that it checks * if the reflected object is accessible when it actually indicates * if the checks for Java language access control are suppressed. * This method may return `false` on a reflected object that is * accessible to the caller. To test if this reflected object is accessible, * it should use {@link #canAccess(Object)}. * * @revised 9 */ isAccessible(): boolean; /** * Test if the caller can access this reflected object. If this reflected * object corresponds to an instance method or field then this method tests * if the caller can access the given `obj` with the reflected object. * For instance methods or fields then the `obj` argument must be an * instance of the {@link Member#getDeclaringClass() declaring class}. For * static members and constructors then `obj` must be `null`. * * This method returns `true` if the `accessible` flag * is set to `true`, i.e. the checks for Java language access control * are suppressed, or if the caller can access the member as * specified in The Java Language Specification, * with the variation noted in the class description. * * @param obj an instance object of the declaring class of this reflected * object if it is an instance method or field * * @return `true` if the caller can access this reflected object. * * @throws IllegalArgumentException * * if this reflected object is a static member or constructor and * the given `obj` is non-`null`, or * if this reflected object is an instance method or field * and the given `obj` is `null` or of type * that is not a subclass of the {@link Member#getDeclaringClass() * declaring class} of the member. * * * @since 9 * @jls 6.6 Access Control * @see #trySetAccessible * @see #setAccessible(boolean) */ canAccess(obj: any): boolean; /** * {@inheritDoc} * * Note that any annotation returned by this method is a * declaration annotation. * * @throws NullPointerException {@inheritDoc} * @since 1.5 */ getAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * * @throws NullPointerException {@inheritDoc} * @since 1.5 */ isAnnotationPresent(annotationClass: Class): boolean; /** * {@inheritDoc} * * Note that any annotations returned by this method are * declaration annotations. * * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getAnnotationsByType(annotationClass: Class): T[]; /** * {@inheritDoc} * * Note that any annotations returned by this method are * declaration annotations. * * @since 1.5 */ get annotations(): Annotation[]; /** * {@inheritDoc} * * Note that any annotation returned by this method is a * declaration annotation. * * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getDeclaredAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * * Note that any annotations returned by this method are * declaration annotations. * * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getDeclaredAnnotationsByType(annotationClass: Class): T[]; /** * {@inheritDoc} * * Note that any annotations returned by this method are * declaration annotations. * * @since 1.5 */ get declaredAnnotations(): Annotation[]; } /** * `AnnotatedParameterizedType` represents the potentially annotated use * of a parameterized type, whose type arguments may themselves represent * annotated uses of types. * * @jls 4.5 Parameterized Types * @since 1.8 */ export class AnnotatedParameterizedType extends AnnotatedType { /** * Returns the potentially annotated actual type arguments of this parameterized type. * * Note that in some cases, the returned array can be empty. This can occur * if this annotated type represents a non-parameterized type nested within * a parameterized type. * * @return the potentially annotated actual type arguments of this parameterized type * @see ParameterizedType#getActualTypeArguments() */ get annotatedActualTypeArguments(): AnnotatedType[]; /** * Returns the potentially annotated type that this type is a member of, if * this type represents a nested type. For example, if this type is * `@TA O.I`, return a representation of `@TA O`. * * Returns `null` if this `AnnotatedType` represents a * top-level class or interface, or a local or anonymous class, or * a primitive type, or void. * * @return an `AnnotatedType` object representing the potentially * annotated type that this type is a member of, or `null` * @throws TypeNotPresentException if the owner type * refers to a non-existent class or interface declaration * @throws MalformedParameterizedTypeException if the owner type * refers to a parameterized type that cannot be instantiated * for any reason * * @since 9 */ get annotatedOwnerType(): AnnotatedType; } /** * Member is an interface that reflects identifying information about * a single member (a field or a method) or a constructor. * * @see java.lang.Class * @see Field * @see Method * @see Constructor * * @author Nakul Saraiya * @since 1.1 */ export class Member { /** * Identifies the set of all public members of a class or interface, * including inherited members. */ static readonly PUBLIC: number; /** * Identifies the set of declared members of a class or interface. * Inherited members are not included. */ static readonly DECLARED: number; /** * Returns the Class object representing the class or interface * that declares the member or constructor represented by this Member. * * @return an object representing the declaring class of the * underlying member */ get declaringClass(): Class; /** * Returns the simple name of the underlying member or constructor * represented by this Member. * * @return the simple name of the underlying member */ get name(): string; /** * Returns the Java language modifiers for the member or * constructor represented by this Member, as an integer. The * Modifier class should be used to decode the modifiers in * the integer. * * @return the Java language modifiers for the underlying member * @see Modifier */ get modifiers(): number; /** * Returns `true` if this member was introduced by * the compiler; returns `false` otherwise. * * @return true if and only if this member was introduced by * the compiler. * @jls 13.1 The Form of a Binary * @since 1.5 */ isSynthetic(): boolean; } /** * A `Field` provides information about, and dynamic access to, a * single field of a class or an interface. The reflected field may * be a class (static) field or an instance field. * * A `Field` permits widening conversions to occur during a get or * set access operation, but throws an `IllegalArgumentException` if a * narrowing conversion would occur. * * @see Member * @see java.lang.Class * @see java.lang.Class#getFields() * @see java.lang.Class#getField(String) * @see java.lang.Class#getDeclaredFields() * @see java.lang.Class#getDeclaredField(String) * * @author Kenneth Russell * @author Nakul Saraiya * @since 1.1 */ export class Field extends AccessibleObject { /** * @throws InaccessibleObjectException {@inheritDoc} * @throws SecurityException {@inheritDoc} */ setAccessible(flag: boolean): void; /** * Returns the `Class` object representing the class or interface * that declares the field represented by this `Field` object. */ get declaringClass(): Class; /** * Returns the name of the field represented by this `Field` object. */ get name(): string; /** * Returns the Java language modifiers for the field represented * by this `Field` object, as an integer. The `Modifier` class should * be used to decode the modifiers. * * @see Modifier */ get modifiers(): number; /** * Returns `true` if this field represents an element of * an enumerated class; returns `false` otherwise. * * @return `true` if and only if this field represents an element of * an enumerated class. * @since 1.5 */ isEnumConstant(): boolean; /** * Returns `true` if this field is a synthetic * field; returns `false` otherwise. * * @return true if and only if this field is a synthetic * field as defined by the Java Language Specification. * @since 1.5 */ isSynthetic(): boolean; /** * Returns a `Class` object that identifies the * declared type for the field represented by this * `Field` object. * * @return a `Class` object identifying the declared * type of the field represented by this object */ get type(): Class; /** * Returns a `Type` object that represents the declared type for * the field represented by this `Field` object. * * If the declared type of the field is a parameterized type, * the `Type` object returned must accurately reflect the * actual type arguments used in the source code. * * If the type of the underlying field is a type variable or a * parameterized type, it is created. Otherwise, it is resolved. * * @return a `Type` object that represents the declared type for * the field represented by this `Field` object * @throws GenericSignatureFormatError if the generic field * signature does not conform to the format specified in * The Java Virtual Machine Specification * @throws TypeNotPresentException if the generic type * signature of the underlying field refers to a non-existent * class or interface declaration * @throws MalformedParameterizedTypeException if the generic * signature of the underlying field refers to a parameterized type * that cannot be instantiated for any reason * @since 1.5 */ get genericType(): Type; /** * Compares this `Field` against the specified object. Returns * true if the objects are the same. Two `Field` objects are the same if * they were declared by the same class and have the same name * and type. */ equals(obj: any): boolean; /** * Returns a hashcode for this `Field`. This is computed as the * exclusive-or of the hashcodes for the underlying field's * declaring class name and its name. */ hashCode(): number; /** * Returns a string describing this `Field`. The format is * the access modifiers for the field, if any, followed * by the field type, followed by a space, followed by * the fully-qualified name of the class declaring the field, * followed by a period, followed by the name of the field. * For example: * * public static final int java.lang.Thread.MIN_PRIORITY * private int java.io.FileDescriptor.fd * * * The modifiers are placed in canonical order as specified by * "The Java Language Specification". This is `public`, * `protected` or `private` first, and then other * modifiers in the following order: `static`, `final`, * `transient`, `volatile`. * * @return a string describing this `Field` * @jls 8.3.1 Field Modifiers */ toString(): string; /** * Returns a string describing this `Field`, including * its generic type. The format is the access modifiers for the * field, if any, followed by the generic field type, followed by * a space, followed by the fully-qualified name of the class * declaring the field, followed by a period, followed by the name * of the field. * * The modifiers are placed in canonical order as specified by * "The Java Language Specification". This is `public`, * `protected` or `private` first, and then other * modifiers in the following order: `static`, `final`, * `transient`, `volatile`. * * @return a string describing this `Field`, including * its generic type * * @since 1.5 * @jls 8.3.1 Field Modifiers */ toGenericString(): string; /** * Returns the value of the field represented by this `Field`, on * the specified object. The value is automatically wrapped in an * object if it has a primitive type. * * The underlying field's value is obtained as follows: * * If the underlying field is a static field, the `obj` argument * is ignored; it may be null. * * Otherwise, the underlying field is an instance field. If the * specified `obj` argument is null, the method throws a * `NullPointerException`. If the specified object is not an * instance of the class or interface declaring the underlying * field, the method throws an `IllegalArgumentException`. * * If this `Field` object is enforcing Java language access control, and * the underlying field is inaccessible, the method throws an * `IllegalAccessException`. * If the underlying field is static, the class that declared the * field is initialized if it has not already been initialized. * * Otherwise, the value is retrieved from the underlying instance * or static field. If the field has a primitive type, the value * is wrapped in an object before being returned, otherwise it is * returned as is. * * If the field is hidden in the type of `obj`, * the field's value is obtained according to the preceding rules. * * @param obj object from which the represented field's value is * to be extracted * @return the value of the represented field in object * `obj`; primitive values are wrapped in an appropriate * object before being returned * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof). * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. */ get(obj: any): any; /** * Gets the value of a static or instance `boolean` field. * * @param obj the object to extract the `boolean` value * from * @return the value of the `boolean` field * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible. * @throws IllegalArgumentException if the specified object is not * an instance of the class or interface declaring the * underlying field (or a subclass or implementor * thereof), or if the field value cannot be * converted to the type `boolean` by a * widening conversion. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#get */ getBoolean(obj: any): boolean; /** * Gets the value of a static or instance `byte` field. * * @param obj the object to extract the `byte` value * from * @return the value of the `byte` field * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible. * @throws IllegalArgumentException if the specified object is not * an instance of the class or interface declaring the * underlying field (or a subclass or implementor * thereof), or if the field value cannot be * converted to the type `byte` by a * widening conversion. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#get */ getByte(obj: any): number; /** * Gets the value of a static or instance field of type * `char` or of another primitive type convertible to * type `char` via a widening conversion. * * @param obj the object to extract the `char` value * from * @return the value of the field converted to type `char` * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible. * @throws IllegalArgumentException if the specified object is not * an instance of the class or interface declaring the * underlying field (or a subclass or implementor * thereof), or if the field value cannot be * converted to the type `char` by a * widening conversion. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#get */ getChar(obj: any): string; /** * Gets the value of a static or instance field of type * `short` or of another primitive type convertible to * type `short` via a widening conversion. * * @param obj the object to extract the `short` value * from * @return the value of the field converted to type `short` * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible. * @throws IllegalArgumentException if the specified object is not * an instance of the class or interface declaring the * underlying field (or a subclass or implementor * thereof), or if the field value cannot be * converted to the type `short` by a * widening conversion. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#get */ getShort(obj: any): number; /** * Gets the value of a static or instance field of type * `int` or of another primitive type convertible to * type `int` via a widening conversion. * * @param obj the object to extract the `int` value * from * @return the value of the field converted to type `int` * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible. * @throws IllegalArgumentException if the specified object is not * an instance of the class or interface declaring the * underlying field (or a subclass or implementor * thereof), or if the field value cannot be * converted to the type `int` by a * widening conversion. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#get */ getInt(obj: any): number; /** * Gets the value of a static or instance field of type * `long` or of another primitive type convertible to * type `long` via a widening conversion. * * @param obj the object to extract the `long` value * from * @return the value of the field converted to type `long` * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible. * @throws IllegalArgumentException if the specified object is not * an instance of the class or interface declaring the * underlying field (or a subclass or implementor * thereof), or if the field value cannot be * converted to the type `long` by a * widening conversion. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#get */ getLong(obj: any): number; /** * Gets the value of a static or instance field of type * `float` or of another primitive type convertible to * type `float` via a widening conversion. * * @param obj the object to extract the `float` value * from * @return the value of the field converted to type `float` * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible. * @throws IllegalArgumentException if the specified object is not * an instance of the class or interface declaring the * underlying field (or a subclass or implementor * thereof), or if the field value cannot be * converted to the type `float` by a * widening conversion. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#get */ getFloat(obj: any): number; /** * Gets the value of a static or instance field of type * `double` or of another primitive type convertible to * type `double` via a widening conversion. * * @param obj the object to extract the `double` value * from * @return the value of the field converted to type `double` * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible. * @throws IllegalArgumentException if the specified object is not * an instance of the class or interface declaring the * underlying field (or a subclass or implementor * thereof), or if the field value cannot be * converted to the type `double` by a * widening conversion. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#get */ getDouble(obj: any): number; /** * Sets the field represented by this `Field` object on the * specified object argument to the specified new value. The new * value is automatically unwrapped if the underlying field has a * primitive type. * * The operation proceeds as follows: * * If the underlying field is static, the `obj` argument is * ignored; it may be null. * * Otherwise the underlying field is an instance field. If the * specified object argument is null, the method throws a * `NullPointerException`. If the specified object argument is not * an instance of the class or interface declaring the underlying * field, the method throws an `IllegalArgumentException`. * * If this `Field` object is enforcing Java language access control, and * the underlying field is inaccessible, the method throws an * `IllegalAccessException`. * * If the underlying field is final, this `Field` object has * write access if and only if the following conditions are met: * * {@link #setAccessible(boolean) setAccessible(true)} has succeeded for * this `Field` object; * the field is non-static; and * the field's declaring class is not a {@linkplain Class#isHidden() * hidden class}; and * the field's declaring class is not a {@linkplain Class#isRecord() * record class}. * * If any of the above checks is not met, this method throws an * `IllegalAccessException`. * * Setting a final field in this way * is meaningful only during deserialization or reconstruction of * instances of classes with blank final fields, before they are * made available for access by other parts of a program. Use in * any other context may have unpredictable effects, including cases * in which other parts of a program continue to use the original * value of this field. * * If the underlying field is of a primitive type, an unwrapping * conversion is attempted to convert the new value to a value of * a primitive type. If this attempt fails, the method throws an * `IllegalArgumentException`. * * If, after possible unwrapping, the new value cannot be * converted to the type of the underlying field by an identity or * widening conversion, the method throws an * `IllegalArgumentException`. * * If the underlying field is static, the class that declared the * field is initialized if it has not already been initialized. * * The field is set to the possibly unwrapped and widened new value. * * If the field is hidden in the type of `obj`, * the field's value is set according to the preceding rules. * * @param obj the object whose field should be modified * @param value the new value for the field of `obj` * being modified * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is inaccessible or final; * or if this `Field` object has no write access. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof), * or if an unwrapping conversion fails. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. */ set(obj: any, value: any): void; /** * Sets the value of a field as a `boolean` on the specified object. * This method is equivalent to * `set(obj, zObj)`, * where `zObj` is a `Boolean` object and * `zObj.booleanValue() == z`. * * @param obj the object whose field should be modified * @param z the new value for the field of `obj` * being modified * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is either inaccessible or final; * or if this `Field` object has no write access. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof), * or if an unwrapping conversion fails. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#set */ setBoolean(obj: any, z: boolean): void; /** * Sets the value of a field as a `byte` on the specified object. * This method is equivalent to * `set(obj, bObj)`, * where `bObj` is a `Byte` object and * `bObj.byteValue() == b`. * * @param obj the object whose field should be modified * @param b the new value for the field of `obj` * being modified * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is either inaccessible or final; * or if this `Field` object has no write access. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof), * or if an unwrapping conversion fails. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#set */ setByte(obj: any, b: number): void; /** * Sets the value of a field as a `char` on the specified object. * This method is equivalent to * `set(obj, cObj)`, * where `cObj` is a `Character` object and * `cObj.charValue() == c`. * * @param obj the object whose field should be modified * @param c the new value for the field of `obj` * being modified * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is either inaccessible or final; * or if this `Field` object has no write access. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof), * or if an unwrapping conversion fails. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#set */ setChar(obj: any, c: string): void; /** * Sets the value of a field as a `short` on the specified object. * This method is equivalent to * `set(obj, sObj)`, * where `sObj` is a `Short` object and * `sObj.shortValue() == s`. * * @param obj the object whose field should be modified * @param s the new value for the field of `obj` * being modified * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is either inaccessible or final; * or if this `Field` object has no write access. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof), * or if an unwrapping conversion fails. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#set */ setShort(obj: any, s: number): void; /** * Sets the value of a field as an `int` on the specified object. * This method is equivalent to * `set(obj, iObj)`, * where `iObj` is an `Integer` object and * `iObj.intValue() == i`. * * @param obj the object whose field should be modified * @param i the new value for the field of `obj` * being modified * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is either inaccessible or final; * or if this `Field` object has no write access. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof), * or if an unwrapping conversion fails. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#set */ setInt(obj: any, i: number): void; /** * Sets the value of a field as a `long` on the specified object. * This method is equivalent to * `set(obj, lObj)`, * where `lObj` is a `Long` object and * `lObj.longValue() == l`. * * @param obj the object whose field should be modified * @param l the new value for the field of `obj` * being modified * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is either inaccessible or final; * or if this `Field` object has no write access. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof), * or if an unwrapping conversion fails. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#set */ setLong(obj: any, l: number): void; /** * Sets the value of a field as a `float` on the specified object. * This method is equivalent to * `set(obj, fObj)`, * where `fObj` is a `Float` object and * `fObj.floatValue() == f`. * * @param obj the object whose field should be modified * @param f the new value for the field of `obj` * being modified * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is either inaccessible or final; * or if this `Field` object has no write access. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof), * or if an unwrapping conversion fails. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#set */ setFloat(obj: any, f: number): void; /** * Sets the value of a field as a `double` on the specified object. * This method is equivalent to * `set(obj, dObj)`, * where `dObj` is a `Double` object and * `dObj.doubleValue() == d`. * * @param obj the object whose field should be modified * @param d the new value for the field of `obj` * being modified * * @throws IllegalAccessException if this `Field` object * is enforcing Java language access control and the underlying * field is either inaccessible or final; * or if this `Field` object has no write access. * @throws IllegalArgumentException if the specified object is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof), * or if an unwrapping conversion fails. * @throws NullPointerException if the specified object is null * and the field is an instance field. * @throws ExceptionInInitializerError if the initialization provoked * by this method fails. * @see Field#set */ setDouble(obj: any, d: number): void; /** * {@inheritDoc} * * @throws NullPointerException {@inheritDoc} * @since 1.5 */ getAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getAnnotationsByType(annotationClass: Class): T[]; /** * {@inheritDoc} */ get declaredAnnotations(): Annotation[]; /** * Returns an AnnotatedType object that represents the use of a type to specify * the declared type of the field represented by this Field. * @return an object representing the declared type of the field * represented by this Field * * @since 1.8 */ get annotatedType(): AnnotatedType; /** * Convenience method to set the `accessible` flag for an * array of reflected objects with a single security check (for efficiency). * * This method may be used to enable access to all reflected objects in * the array when access to each reflected object can be enabled as * specified by {@link #setAccessible(boolean) setAccessible(boolean)}. * * If there is a security manager, its * `checkPermission` method is first called with a * `ReflectPermission("suppressAccessChecks")` permission. * * A `SecurityException` is also thrown if any of the elements of * the input `array` is a {@link java.lang.reflect.Constructor} * object for the class `java.lang.Class` and `flag` is true. * * @param array the array of AccessibleObjects * @param flag the new value for the `accessible` flag * in each object * @throws InaccessibleObjectException if access cannot be enabled for all * objects in the array * @throws SecurityException if the request is denied by the security manager * or an element in the array is a constructor for ` * java.lang.Class` * @see SecurityManager#checkPermission * @see ReflectPermission * @revised 9 */ static setAccessible(array: AccessibleObject[], flag: boolean): void; /** * {@inheritDoc} * * Note that any annotations returned by this method are * declaration annotations. * * @since 1.5 */ get annotations(): Annotation[]; } export interface Field extends AccessibleObject, Member {} /** * Thrown when {@link java.lang.reflect.Executable#getParameters the * java.lang.reflect package} attempts to read method parameters from * a class file and determines that one or more parameters are * malformed. * * The following is a list of conditions under which this exception * can be thrown: * * The number of parameters (parameter_count) is wrong for the method * A constant pool index is out of bounds. * A constant pool index does not refer to a UTF-8 entry * A parameter's name is "", or contains an illegal character * The flags field contains an illegal flag (something other than * FINAL, SYNTHETIC, or MANDATED) * * * See {@link java.lang.reflect.Executable#getParameters} for more * information. * * @see java.lang.reflect.Executable#getParameters * @since 1.8 */ export class MalformedParametersException extends RuntimeException { /** * Create a `MalformedParametersException` with an empty * reason. */ constructor(); /** * Create a `MalformedParametersException`. * * @param reason The reason for the exception. */ constructor(reason: string); } /** * A shared superclass for the common functionality of {@link Method} * and {@link Constructor}. * * @since 1.8 */ export class Executable extends AccessibleObject { /** * Returns the `Class` object representing the class or interface * that declares the executable represented by this object. */ get declaringClass(): Class; /** * Returns the name of the executable represented by this object. */ get name(): string; /** * Returns the Java language {@linkplain Modifier modifiers} for * the executable represented by this object. */ get modifiers(): number; /** * Returns an array of `TypeVariable` objects that represent the * type variables declared by the generic declaration represented by this * `GenericDeclaration` object, in declaration order. Returns an * array of length 0 if the underlying generic declaration declares no type * variables. * * @return an array of `TypeVariable` objects that represent * the type variables declared by this generic declaration * @throws GenericSignatureFormatError if the generic * signature of this generic declaration does not conform to * the format specified in * The Java Virtual Machine Specification */ get typeParameters(): TypeVariable[]; /** * Returns an array of `Class` objects that represent the formal * parameter types, in declaration order, of the executable * represented by this object. Returns an array of length * 0 if the underlying executable takes no parameters. * Note that the constructors of some inner classes * may have an implicitly declared parameter in addition to * explicitly declared ones. * * @return the parameter types for the executable this object * represents */ get parameterTypes(): Class[]; /** * Returns the number of formal parameters (whether explicitly * declared or implicitly declared or neither) for the executable * represented by this object. * * @return The number of formal parameters for the executable this * object represents */ get parameterCount(): number; /** * Returns an array of `Type` objects that represent the formal * parameter types, in declaration order, of the executable represented by * this object. Returns an array of length 0 if the * underlying executable takes no parameters. * Note that the constructors of some inner classes * may have an implicitly declared parameter in addition to * explicitly declared ones. * * If a formal parameter type is a parameterized type, * the `Type` object returned for it must accurately reflect * the actual type arguments used in the source code. * * If a formal parameter type is a type variable or a parameterized * type, it is created. Otherwise, it is resolved. * * @return an array of `Type`s that represent the formal * parameter types of the underlying executable, in declaration order * @throws GenericSignatureFormatError * if the generic method signature does not conform to the format * specified in * The Java Virtual Machine Specification * @throws TypeNotPresentException if any of the parameter * types of the underlying executable refers to a non-existent type * declaration * @throws MalformedParameterizedTypeException if any of * the underlying executable's parameter types refer to a parameterized * type that cannot be instantiated for any reason */ get genericParameterTypes(): Type[]; /** * Returns an array of `Parameter` objects that represent * all the parameters to the underlying executable represented by * this object. Returns an array of length 0 if the executable * has no parameters. * * The parameters of the underlying executable do not necessarily * have unique names, or names that are legal identifiers in the * Java programming language (JLS 3.8). * * @throws MalformedParametersException if the class file contains * a MethodParameters attribute that is improperly formatted. * @return an array of `Parameter` objects representing all * the parameters to the executable this object represents. */ get parameters(): Parameter[]; /** * Returns an array of `Class` objects that represent the * types of exceptions declared to be thrown by the underlying * executable represented by this object. Returns an array of * length 0 if the executable declares no exceptions in its ` * throws` clause. * * @return the exception types declared as being thrown by the * executable this object represents */ get exceptionTypes(): Class[]; /** * Returns an array of `Type` objects that represent the * exceptions declared to be thrown by this executable object. * Returns an array of length 0 if the underlying executable declares * no exceptions in its `throws` clause. * * If an exception type is a type variable or a parameterized * type, it is created. Otherwise, it is resolved. * * @return an array of Types that represent the exception types * thrown by the underlying executable * @throws GenericSignatureFormatError * if the generic method signature does not conform to the format * specified in * The Java Virtual Machine Specification * @throws TypeNotPresentException if the underlying executable's * `throws` clause refers to a non-existent type declaration * @throws MalformedParameterizedTypeException if * the underlying executable's `throws` clause refers to a * parameterized type that cannot be instantiated for any reason */ get genericExceptionTypes(): Type[]; /** * Returns a string describing this `Executable`, including * any type parameters. * @return a string describing this `Executable`, including * any type parameters */ toGenericString(): string; /** * Returns `true` if this executable was declared to take a * variable number of arguments; returns `false` otherwise. * * @return `true` if an only if this executable was declared * to take a variable number of arguments. */ isVarArgs(): boolean; /** * Returns `true` if this executable is a synthetic * construct; returns `false` otherwise. * * @return true if and only if this executable is a synthetic * construct as defined by * The Java Language Specification. * @jls 13.1 The Form of a Binary */ isSynthetic(): boolean; /** * Returns an array of arrays of `Annotation`s that * represent the annotations on the formal parameters, in * declaration order, of the `Executable` represented by * this object. Synthetic and mandated parameters (see * explanation below), such as the outer "this" parameter to an * inner class constructor will be represented in the returned * array. If the executable has no parameters (meaning no formal, * no synthetic, and no mandated parameters), a zero-length array * will be returned. If the `Executable` has one or more * parameters, a nested array of length zero is returned for each * parameter with no annotations. The annotation objects contained * in the returned arrays are serializable. The caller of this * method is free to modify the returned arrays; it will have no * effect on the arrays returned to other callers. * * A compiler may add extra parameters that are implicitly * declared in source ("mandated"), as well as parameters that * are neither implicitly nor explicitly declared in source * ("synthetic") to the parameter list for a method. See {@link * java.lang.reflect.Parameter} for more information. * * Note that any annotations returned by this method are * declaration annotations. * * @see java.lang.reflect.Parameter * @see java.lang.reflect.Parameter#getAnnotations * @return an array of arrays that represent the annotations on * the formal and implicit parameters, in declaration order, of * the executable represented by this object */ get parameterAnnotations(): Annotation[][]; /** * {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ getAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * * @throws NullPointerException {@inheritDoc} */ getAnnotationsByType(annotationClass: Class): T[]; /** * Returns annotations that are directly present on this element. * This method ignores inherited annotations. * * If there are no annotations directly present on this element, * the return value is an array of length 0. * * The caller of this method is free to modify the returned array; it will * have no effect on the arrays returned to other callers. * * @return annotations directly present on this element * @since 1.5 */ get declaredAnnotations(): Annotation[]; /** * Returns an `AnnotatedType` object that represents the use of a type to * specify the return type of the method/constructor represented by this * Executable. * * If this `Executable` object represents a constructor, the ` * AnnotatedType` object represents the type of the constructed object. * * If this `Executable` object represents a method, the ` * AnnotatedType` object represents the use of a type to specify the return * type of the method. * * @return an object representing the return type of the method * or constructor represented by this `Executable` */ get annotatedReturnType(): AnnotatedType; /** * Returns an `AnnotatedType` object that represents the use of a * type to specify the receiver type of the method/constructor represented * by this `Executable` object. * * The receiver type of a method/constructor is available only if the * method/constructor has a receiver parameter (JLS 8.4.1). If this ` * Executable` object represents an instance method or represents a * constructor of an inner member class, and the * method/constructor either has no receiver parameter or has a * receiver parameter with no annotations on its type, then the return * value is an `AnnotatedType` object representing an element with no * annotations. * * If this `Executable` object represents a static method or * represents a constructor of a top level, static member, local, or * anonymous class, then the return value is null. * * @return an object representing the receiver type of the method or * constructor represented by this `Executable` or `null` if * this `Executable` can not have a receiver parameter * * @jls 8.4 Method Declarations * @jls 8.4.1 Formal Parameters * @jls 8.8 Constructor Declarations */ get annotatedReceiverType(): AnnotatedType; /** * Returns an array of `AnnotatedType` objects that represent the use * of types to specify formal parameter types of the method/constructor * represented by this Executable. The order of the objects in the array * corresponds to the order of the formal parameter types in the * declaration of the method/constructor. * * Returns an array of length 0 if the method/constructor declares no * parameters. * Note that the constructors of some inner classes * may have an implicitly declared parameter in addition to * explicitly declared ones. * * @return an array of objects representing the types of the * formal parameters of the method or constructor represented by this * `Executable` */ get annotatedParameterTypes(): AnnotatedType[]; /** * Returns an array of `AnnotatedType` objects that represent the use * of types to specify the declared exceptions of the method/constructor * represented by this Executable. The order of the objects in the array * corresponds to the order of the exception types in the declaration of * the method/constructor. * * Returns an array of length 0 if the method/constructor declares no * exceptions. * * @return an array of objects representing the declared * exceptions of the method or constructor represented by this ` * Executable` */ get annotatedExceptionTypes(): AnnotatedType[]; } export interface Executable extends AccessibleObject, Member, GenericDeclaration {} /** * The Permission class for reflective operations. * * The following table * provides a summary description of what the permission allows, * and discusses the risks of granting code the permission. * * * Table shows permission target name, what the permission allows, and associated risks * * * Permission Target Name * What the Permission Allows * Risks of Allowing this Permission * * * * * * suppressAccessChecks * ability to suppress the standard Java language access checks * on fields and methods in a class; allow access not only public members * but also allow access to default (package) access, protected, * and private members. * This is dangerous in that information (possibly confidential) and * methods normally unavailable would be accessible to malicious code. * * * newProxyInPackage.{package name} * ability to create a proxy instance in the specified package of which * the non-public interface that the proxy class implements. * This gives code access to classes in packages to which it normally * does not have access and the dynamic proxy class is in the system * protection domain. Malicious code may use these classes to * help in its attempt to compromise security in the system. * * * * * * @see java.security.Permission * @see java.security.BasicPermission * @see AccessibleObject * @see Field#get * @see Field#set * @see Method#invoke * @see Constructor#newInstance * @see Proxy#newProxyInstance * * @since 1.2 */ export class ReflectPermission extends BasicPermission { /** * Constructs a ReflectPermission with the specified name. * * @param name the name of the ReflectPermission * * @throws NullPointerException if `name` is `null`. * @throws IllegalArgumentException if `name` is empty. */ constructor(name: string); /** * Constructs a ReflectPermission with the specified name and actions. * The actions should be null; they are ignored. * * @param name the name of the ReflectPermission * * @param actions should be null * * @throws NullPointerException if `name` is `null`. * @throws IllegalArgumentException if `name` is empty. */ constructor(name: string, actions: string); } /** * InvocationTargetException is a checked exception that wraps * an exception thrown by an invoked method or constructor. * * As of release 1.4, this exception has been retrofitted to conform to * the general purpose exception-chaining mechanism. The "target exception" * that is provided at construction time and accessed via the * {@link #getTargetException()} method is now known as the cause, * and may be accessed via the {@link Throwable#getCause()} method, * as well as the aforementioned "legacy method." * * @see Method * @see Constructor * @since 1.1 */ export class InvocationTargetException extends ReflectiveOperationException { /** * Constructs a InvocationTargetException with a target exception. * * @param target the target exception */ constructor(target: Throwable); /** * Constructs a InvocationTargetException with a target exception * and a detail message. * * @param target the target exception * @param s the detail message */ constructor(target: Throwable, s: string); /** * Get the thrown target exception. * * This method predates the general-purpose exception chaining facility. * The {@link Throwable#getCause()} method is now the preferred means of * obtaining this information. * * @return the thrown target exception (cause of this exception). */ get targetException(): Throwable; /** * Returns the cause of this exception (the thrown target exception, * which may be `null`). * * @return the cause of this exception. * @since 1.4 */ get cause(): Throwable; } /** * * `Proxy` provides static methods for creating objects that act like instances * of interfaces but allow for customized method invocation. * To create a proxy instance for some interface `Foo`: * {@code * InvocationHandler handler = new MyInvocationHandler(...); * Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), * new Class[] { Foo.class }, * handler); * } * * * A proxy class is a class created at runtime that implements a specified * list of interfaces, known as proxy interfaces. A proxy instance * is an instance of a proxy class. * * Each proxy instance has an associated invocation handler * object, which implements the interface {@link InvocationHandler}. * A method invocation on a proxy instance through one of its proxy * interfaces will be dispatched to the {@link InvocationHandler#invoke * invoke} method of the instance's invocation handler, passing the proxy * instance, a `java.lang.reflect.Method` object identifying * the method that was invoked, and an array of type `Object` * containing the arguments. The invocation handler processes the * encoded method invocation as appropriate and the result that it * returns will be returned as the result of the method invocation on * the proxy instance. * * A proxy class has the following properties: * * * The unqualified name of a proxy class is unspecified. The space * of class names that begin with the string `"$Proxy"` * should be, however, reserved for proxy classes. * * The package and module in which a proxy class is defined is specified * below. * * A proxy class is final and non-abstract. * * A proxy class extends `java.lang.reflect.Proxy`. * * A proxy class implements exactly the interfaces specified at its * creation, in the same order. Invoking {@link Class#getInterfaces() getInterfaces} * on its `Class` object will return an array containing the same * list of interfaces (in the order specified at its creation), invoking * {@link Class#getMethods getMethods} on its `Class` object will return * an array of `Method` objects that include all of the * methods in those interfaces, and invoking `getMethod` will * find methods in the proxy interfaces as would be expected. * * The {@link java.security.ProtectionDomain} of a proxy class * is the same as that of system classes loaded by the bootstrap class * loader, such as `java.lang.Object`, because the code for a * proxy class is generated by trusted system code. This protection * domain will typically be granted `java.security.AllPermission`. * * The {@link Proxy#isProxyClass Proxy.isProxyClass} method can be used * to determine if a given class is a proxy class. * * * A proxy instance has the following properties: * * * Given a proxy instance `proxy` and one of the * interfaces, `Foo`, implemented by its proxy class, the * following expression will return true: * * `proxy instanceof Foo` * * and the following cast operation will succeed (rather than throwing * a `ClassCastException`): * * `(Foo) proxy` * * * Each proxy instance has an associated invocation handler, the one * that was passed to its constructor. The static * {@link Proxy#getInvocationHandler Proxy.getInvocationHandler} method * will return the invocation handler associated with the proxy instance * passed as its argument. * * An interface method invocation on a proxy instance will be * encoded and dispatched to the invocation handler's {@link * InvocationHandler#invoke invoke} method as described in the * documentation for that method. * * A proxy interface may define a default method or inherit * a default method from its superinterface directly or indirectly. * An invocation handler can invoke a default method of a proxy interface * by calling {@link InvocationHandler#invokeDefault(Object, Method, Object...) * InvocationHandler::invokeDefault}. * * An invocation of the `hashCode`, * `equals`, or `toString` methods declared in * `java.lang.Object` on a proxy instance will be encoded and * dispatched to the invocation handler's `invoke` method in * the same manner as interface method invocations are encoded and * dispatched, as described above. The declaring class of the * `Method` object passed to `invoke` will be * `java.lang.Object`. Other public methods of a proxy * instance inherited from `java.lang.Object` are not * overridden by a proxy class, so invocations of those methods behave * like they do for instances of `java.lang.Object`. * * * Package and Module Membership of Proxy Class * * The package and module to which a proxy class belongs are chosen such that * the accessibility of the proxy class is in line with the accessibility of * the proxy interfaces. Specifically, the package and the module membership * of a proxy class defined via the * {@link Proxy#getProxyClass(ClassLoader, Class[])} or * {@link Proxy#newProxyInstance(ClassLoader, Class[], InvocationHandler)} * methods is specified as follows: * * * If all the proxy interfaces are in exported or open * packages: * * if all the proxy interfaces are public, then the proxy class is * public in an unconditionally exported but non-open package. * The name of the package and the module are unspecified. * * if at least one of all the proxy interfaces is non-public, then * the proxy class is non-public in the package and module of the * non-public interfaces. All the non-public interfaces must be in the same * package and module; otherwise, proxying them is * not possible. * * * If at least one proxy interface is in a package that is * non-exported and non-open: * * if all the proxy interfaces are public, then the proxy class is * public in a non-exported, non-open package of * dynamic module. * The names of the package and the module are unspecified. * * if at least one of all the proxy interfaces is non-public, then * the proxy class is non-public in the package and module of the * non-public interfaces. All the non-public interfaces must be in the same * package and module; otherwise, proxying them is * not possible. * * * * * * Note that if proxy interfaces with a mix of accessibilities -- for example, * an exported public interface and a non-exported non-public interface -- are * proxied by the same instance, then the proxy class's accessibility is * governed by the least accessible proxy interface. * * Note that it is possible for arbitrary code to obtain access to a proxy class * in an open package with {@link AccessibleObject#setAccessible setAccessible}, * whereas a proxy class in a non-open package is never accessible to * code outside the module of the proxy class. * * * Throughout this specification, a "non-exported package" refers to a package * that is not exported to all modules, and a "non-open package" refers to * a package that is not open to all modules. Specifically, these terms refer to * a package that either is not exported/open by its containing module or is * exported/open in a qualified fashion by its containing module. * * Dynamic Modules * * A dynamic module is a named module generated at runtime. A proxy class * defined in a dynamic module is encapsulated and not accessible to any module. * Calling {@link Constructor#newInstance(Object...)} on a proxy class in * a dynamic module will throw `IllegalAccessException`; * `Proxy.newProxyInstance` method should be used instead. * * * A dynamic module can read the modules of all of the superinterfaces of a proxy * class and the modules of the classes and interfaces referenced by * all public method signatures of a proxy class. If a superinterface or * a referenced class or interface, say `T`, is in a non-exported package, * the {@linkplain Module module} of `T` is updated to export the * package of `T` to the dynamic module. * * Methods Duplicated in Multiple Proxy Interfaces * * When two or more proxy interfaces contain a method with * the same name and parameter signature, the order of the proxy class's * interfaces becomes significant. When such a duplicate method * is invoked on a proxy instance, the `Method` object passed * to the invocation handler will not necessarily be the one whose * declaring class is assignable from the reference type of the interface * that the proxy's method was invoked through. This limitation exists * because the corresponding method implementation in the generated proxy * class cannot determine which interface it was invoked through. * Therefore, when a duplicate method is invoked on a proxy instance, * the `Method` object for the method in the foremost interface * that contains the method (either directly or inherited through a * superinterface) in the proxy class's list of interfaces is passed to * the invocation handler's `invoke` method, regardless of the * reference type through which the method invocation occurred. * * If a proxy interface contains a method with the same name and * parameter signature as the `hashCode`, `equals`, * or `toString` methods of `java.lang.Object`, * when such a method is invoked on a proxy instance, the * `Method` object passed to the invocation handler will have * `java.lang.Object` as its declaring class. In other words, * the public, non-final methods of `java.lang.Object` * logically precede all of the proxy interfaces for the determination of * which `Method` object to pass to the invocation handler. * * Note also that when a duplicate method is dispatched to an * invocation handler, the `invoke` method may only throw * checked exception types that are assignable to one of the exception * types in the `throws` clause of the method in all of * the proxy interfaces that it can be invoked through. If the * `invoke` method throws a checked exception that is not * assignable to any of the exception types declared by the method in one * of the proxy interfaces that it can be invoked through, then an * unchecked `UndeclaredThrowableException` will be thrown by * the invocation on the proxy instance. This restriction means that not * all of the exception types returned by invoking * `getExceptionTypes` on the `Method` object * passed to the `invoke` method can necessarily be thrown * successfully by the `invoke` method. * * @author Peter Jones * @see InvocationHandler * @since 1.3 * @revised 9 */ export class Proxy extends Serializable { /** * Returns the `java.lang.Class` object for a proxy class * given a class loader and an array of interfaces. The proxy class * will be defined by the specified class loader and will implement * all of the supplied interfaces. If any of the given interfaces * is non-public, the proxy class will be non-public. If a proxy class * for the same permutation of interfaces has already been defined by the * class loader, then the existing proxy class will be returned; otherwise, * a proxy class for those interfaces will be generated dynamically * and defined by the class loader. * * @param loader the class loader to define the proxy class * @param interfaces the list of interfaces for the proxy class * to implement * @return a proxy class that is defined in the specified class loader * and that implements the specified interfaces * @throws IllegalArgumentException if any of the * restrictions on the parameters are violated * @throws SecurityException if a security manager, s, is present * and any of the following conditions is met: * * the given `loader` is `null` and * the caller's class loader is not `null` and the * invocation of {@link SecurityManager#checkPermission * s.checkPermission} with * `RuntimePermission("getClassLoader")` permission * denies access. * for each proxy interface, `intf`, * the caller's class loader is not the same as or an * ancestor of the class loader for `intf` and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to `intf`. * * @throws NullPointerException if the `interfaces` array * argument or any of its elements are `null` * * @deprecated Proxy classes generated in a named module are encapsulated * and not accessible to code outside its module. * {@link Constructor#newInstance(Object...) Constructor.newInstance} * will throw `IllegalAccessException` when it is called on * an inaccessible proxy class. * Use {@link #newProxyInstance(ClassLoader, Class[], InvocationHandler)} * to create a proxy instance instead. * * @see Package and Module Membership of Proxy Class * @revised 9 */ static getProxyClass(loader: ClassLoader, ...interfaces: Class[]): Class; /** * Returns a proxy instance for the specified interfaces * that dispatches method invocations to the specified invocation * handler. * * `IllegalArgumentException` will be thrown * if any of the following restrictions is violated: * * All of `Class` objects in the given `interfaces` array * must represent {@linkplain Class#isHidden() non-hidden} interfaces, * not classes or primitive types. * * No two elements in the `interfaces` array may * refer to identical `Class` objects. * * All of the interface types must be visible by name through the * specified class loader. In other words, for class loader * `cl` and every interface `i`, the following * expression must be true: * `Class.forName(i.getName(), false, cl) == i` * * All of the types referenced by all * public method signatures of the specified interfaces * and those inherited by their superinterfaces * must be visible by name through the specified class loader. * * All non-public interfaces must be in the same package * and module, defined by the specified class loader and * the module of the non-public interfaces can access all of * the interface types; otherwise, it would not be possible for * the proxy class to implement all of the interfaces, * regardless of what package it is defined in. * * For any set of member methods of the specified interfaces * that have the same signature: * * If the return type of any of the methods is a primitive * type or void, then all of the methods must have that same * return type. * Otherwise, one of the methods must have a return type that * is assignable to all of the return types of the rest of the * methods. * * * The resulting proxy class must not exceed any limits imposed * on classes by the virtual machine. For example, the VM may limit * the number of interfaces that a class may implement to 65535; in * that case, the size of the `interfaces` array must not * exceed 65535. * * * Note that the order of the specified proxy interfaces is * significant: two requests for a proxy class with the same combination * of interfaces but in a different order will result in two distinct * proxy classes. * * @param loader the class loader to define the proxy class * @param interfaces the list of interfaces for the proxy class * to implement * @param h the invocation handler to dispatch method invocations to * @return a proxy instance with the specified invocation handler of a * proxy class that is defined by the specified class loader * and that implements the specified interfaces * @throws IllegalArgumentException if any of the * restrictions on the parameters are violated * @throws SecurityException if a security manager, s, is present * and any of the following conditions is met: * * the given `loader` is `null` and * the caller's class loader is not `null` and the * invocation of {@link SecurityManager#checkPermission * s.checkPermission} with * `RuntimePermission("getClassLoader")` permission * denies access; * for each proxy interface, `intf`, * the caller's class loader is not the same as or an * ancestor of the class loader for `intf` and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to `intf`; * any of the given proxy interfaces is non-public and the * caller class is not in the same {@linkplain Package runtime package} * as the non-public interface and the invocation of * {@link SecurityManager#checkPermission s.checkPermission} with * `ReflectPermission("newProxyInPackage.{package name`")} * permission denies access. * * @throws NullPointerException if the `interfaces` array * argument or any of its elements are `null`, or * if the invocation handler, `h`, is * `null` * * @see Package and Module Membership of Proxy Class * @revised 9 */ static newProxyInstance(loader: ClassLoader, interfaces: Class[], h: InvocationHandler): any; /** * Returns true if the given class is a proxy class. * * @implNote The reliability of this method is important for the ability * to use it to make security decisions, so its implementation should * not just test if the class in question extends `Proxy`. * * @param cl the class to test * @return `true` if the class is a proxy class and * `false` otherwise * @throws NullPointerException if `cl` is `null` * * @revised 9 */ static isProxyClass(cl: Class): boolean; /** * Returns the invocation handler for the specified proxy instance. * * @param proxy the proxy instance to return the invocation handler for * @return the invocation handler for the proxy instance * @throws IllegalArgumentException if the argument is not a * proxy instance * @throws SecurityException if a security manager, s, is present * and the caller's class loader is not the same as or an * ancestor of the class loader for the invocation handler * and invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the invocation * handler's class. */ static getInvocationHandler(proxy: any): InvocationHandler; } /** * WildcardType represents a wildcard type expression, such as * `?`, `? extends Number`, or `? super Integer`. * * @jls 4.5.1 Type Arguments of Parameterized Types * @since 1.5 */ export class WildcardType extends Type { /** * Returns an array of `Type` objects representing the upper * bound(s) of this type variable. If no upper bound is * explicitly declared, the upper bound is `Object`. * * For each upper bound B : * * if B is a parameterized type or a type variable, it is created, * (see {@link java.lang.reflect.ParameterizedType ParameterizedType} * for the details of the creation process for parameterized types). * Otherwise, B is resolved. * * * @apiNote While to date a wildcard may have at most one upper * bound, callers of this method should be written to accommodate * multiple bounds. * * @return an array of Types representing the upper bound(s) of this * type variable * @throws TypeNotPresentException if any of the * bounds refers to a non-existent type declaration * @throws MalformedParameterizedTypeException if any of the * bounds refer to a parameterized type that cannot be instantiated * for any reason */ get upperBounds(): Type[]; /** * Returns an array of `Type` objects representing the * lower bound(s) of this type variable. If no lower bound is * explicitly declared, the lower bound is the type of `null`. * In this case, a zero length array is returned. * * For each lower bound B : * * if B is a parameterized type or a type variable, it is created, * (see {@link java.lang.reflect.ParameterizedType ParameterizedType} * for the details of the creation process for parameterized types). * Otherwise, B is resolved. * * * @apiNote While to date a wildcard may have at most one lower * bound, callers of this method should be written to accommodate * multiple bounds. * * @return an array of Types representing the lower bound(s) of this * type variable * @throws TypeNotPresentException if any of the * bounds refers to a non-existent type declaration * @throws MalformedParameterizedTypeException if any of the * bounds refer to a parameterized type that cannot be instantiated * for any reason */ get lowerBounds(): Type[]; } /** * `AnnotatedArrayType` represents the potentially annotated use of an * array type, whose component type may itself represent the annotated use of a * type. * * @jls 10.1 Array Types * @since 1.8 */ export class AnnotatedArrayType extends AnnotatedType { /** * Returns the potentially annotated generic component type of this array type. * * @return the potentially annotated generic component type of this array type * @see GenericArrayType#getGenericComponentType() */ get annotatedGenericComponentType(): AnnotatedType; /** * Returns the potentially annotated type that this type is a member of, if * this type represents a nested class or interface. For example, if this * type is `@TA O.I`, return a representation of `@TA O`. * * Returns `null` for an `AnnotatedType` that is an instance * of `AnnotatedArrayType`. * * @return `null` * * @since 9 */ get annotatedOwnerType(): AnnotatedType; } /** * Type is the common superinterface for all types in the Java * programming language. These include raw types, parameterized types, * array types, type variables and primitive types. * * @jls 4.1 The Kinds of Types and Values * @jls 4.2 Primitive Types and Values * @jls 4.3 Reference Types and Values * @jls 4.4 Type Variables * @jls 4.5 Parameterized Types * @jls 4.8 Raw Types * @jls 4.9 Intersection Types * @jls 10.1 Array Types * @since 1.5 */ export class Type { /** * Returns a string describing this type, including information * about any type parameters. * * @implSpec The default implementation calls `toString`. * * @return a string describing this type * @since 1.8 */ get typeName(): string; } /** * Thrown when a semantically malformed parameterized type is * encountered by a reflective method that needs to instantiate it. * For example, if the number of type arguments to a parameterized type * is wrong. * * @since 1.5 */ export class MalformedParameterizedTypeException extends RuntimeException { /** * Constructs a `MalformedParameterizedTypeException` with * no detail message. */ constructor(); /** * Constructs a `MalformedParameterizedTypeException` with * the given detail message. * @param message the detail message; may be `null` */ constructor(message: string); } /** * The Modifier class provides `static` methods and * constants to decode class and member access modifiers. The sets of * modifiers are represented as integers with distinct bit positions * representing different modifiers. The values for the constants * representing the modifiers are taken from the tables in sections * {@jvms 4.1}, {@jvms 4.4}, {@jvms 4.5}, and {@jvms 4.7} of * The Java Virtual Machine Specification. * * @see Class#getModifiers() * @see Member#getModifiers() * * @author Nakul Saraiya * @author Kenneth Russell * @since 1.1 */ export class Modifier { /** * Return `true` if the integer argument includes the * `public` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `public` modifier; `false` otherwise. */ static isPublic(mod: number): boolean; /** * Return `true` if the integer argument includes the * `private` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `private` modifier; `false` otherwise. */ static isPrivate(mod: number): boolean; /** * Return `true` if the integer argument includes the * `protected` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `protected` modifier; `false` otherwise. */ static isProtected(mod: number): boolean; /** * Return `true` if the integer argument includes the * `static` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `static` modifier; `false` otherwise. */ static isStatic(mod: number): boolean; /** * Return `true` if the integer argument includes the * `final` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `final` modifier; `false` otherwise. */ static isFinal(mod: number): boolean; /** * Return `true` if the integer argument includes the * `synchronized` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `synchronized` modifier; `false` otherwise. */ static isSynchronized(mod: number): boolean; /** * Return `true` if the integer argument includes the * `volatile` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `volatile` modifier; `false` otherwise. */ static isVolatile(mod: number): boolean; /** * Return `true` if the integer argument includes the * `transient` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `transient` modifier; `false` otherwise. */ static isTransient(mod: number): boolean; /** * Return `true` if the integer argument includes the * `native` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `native` modifier; `false` otherwise. */ static isNative(mod: number): boolean; /** * Return `true` if the integer argument includes the * `interface` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `interface` modifier; `false` otherwise. */ static isInterface(mod: number): boolean; /** * Return `true` if the integer argument includes the * `abstract` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `abstract` modifier; `false` otherwise. */ static isAbstract(mod: number): boolean; /** * Return `true` if the integer argument includes the * `strictfp` modifier, `false` otherwise. * * @param mod a set of modifiers * @return `true` if `mod` includes the * `strictfp` modifier; `false` otherwise. */ static isStrict(mod: number): boolean; /** * Return a string describing the access modifier flags in * the specified modifier. For example: * * public final synchronized strictfp * * The modifier names are returned in an order consistent with the * suggested modifier orderings given in sections 8.1.1, 8.3.1, 8.4.3, 8.8.3, and 9.1.1 of * The Java Language Specification. * The full modifier ordering used by this method is: * {@code * public protected private abstract static final transient * volatile synchronized native strictfp * interface } * The `interface` modifier discussed in this class is * not a true modifier in the Java language and it appears after * all other modifiers listed by this method. This method may * return a string of modifiers that are not valid modifiers of a * Java entity; in other words, no checking is done on the * possible validity of the combination of modifiers represented * by the input. * * Note that to perform such checking for a known kind of entity, * such as a constructor or method, first AND the argument of * `toString` with the appropriate mask from a method like * {@link #constructorModifiers} or {@link #methodModifiers}. * * @param mod a set of modifiers * @return a string representation of the set of modifiers * represented by `mod` */ static toString(mod: number): string; /** * The `int` value representing the `public` * modifier. */ static readonly PUBLIC: number; /** * The `int` value representing the `private` * modifier. */ static readonly PRIVATE: number; /** * The `int` value representing the `protected` * modifier. */ static readonly PROTECTED: number; /** * The `int` value representing the `static` * modifier. */ static readonly STATIC: number; /** * The `int` value representing the `final` * modifier. */ static readonly FINAL: number; /** * The `int` value representing the `synchronized` * modifier. */ static readonly SYNCHRONIZED: number; /** * The `int` value representing the `volatile` * modifier. */ static readonly VOLATILE: number; /** * The `int` value representing the `transient` * modifier. */ static readonly TRANSIENT: number; /** * The `int` value representing the `native` * modifier. */ static readonly NATIVE: number; /** * The `int` value representing the `interface` * modifier. */ static readonly INTERFACE: number; /** * The `int` value representing the `abstract` * modifier. */ static readonly ABSTRACT: number; /** * The `int` value representing the `strictfp` * modifier. */ static readonly STRICT: number; /** * Return an `int` value OR-ing together the source language * modifiers that can be applied to a class. * @return an `int` value OR-ing together the source language * modifiers that can be applied to a class. * * @jls 8.1.1 Class Modifiers * @since 1.7 */ static classModifiers(): number; /** * Return an `int` value OR-ing together the source language * modifiers that can be applied to an interface. * @return an `int` value OR-ing together the source language * modifiers that can be applied to an interface. * * @jls 9.1.1 Interface Modifiers * @since 1.7 */ static interfaceModifiers(): number; /** * Return an `int` value OR-ing together the source language * modifiers that can be applied to a constructor. * @return an `int` value OR-ing together the source language * modifiers that can be applied to a constructor. * * @jls 8.8.3 Constructor Modifiers * @since 1.7 */ static constructorModifiers(): number; /** * Return an `int` value OR-ing together the source language * modifiers that can be applied to a method. * @return an `int` value OR-ing together the source language * modifiers that can be applied to a method. * * @jls 8.4.3 Method Modifiers * @since 1.7 */ static methodModifiers(): number; /** * Return an `int` value OR-ing together the source language * modifiers that can be applied to a field. * @return an `int` value OR-ing together the source language * modifiers that can be applied to a field. * * @jls 8.3.1 Field Modifiers * @since 1.7 */ static fieldModifiers(): number; /** * Return an `int` value OR-ing together the source language * modifiers that can be applied to a parameter. * @return an `int` value OR-ing together the source language * modifiers that can be applied to a parameter. * * @jls 8.4.1 Formal Parameters * @since 1.8 */ static parameterModifiers(): number; } /** * Thrown when a syntactically malformed signature attribute is * encountered by a reflective method that needs to interpret the generic * signature information for a class or interface, method or constructor. * * @since 1.5 */ export class GenericSignatureFormatError extends ClassFormatError { /** * Constructs a new `GenericSignatureFormatError`. * */ constructor(); /** * Constructs a new `GenericSignatureFormatError` with the * specified message. * * @param message the detail message, may be `null` */ constructor(message: string); } /** * `AnnotatedWildcardType` represents the potentially annotated use of a * wildcard type argument, whose upper or lower bounds may themselves represent * annotated uses of types. * * @jls 4.5.1 Type Arguments of Parameterized Types * @since 1.8 */ export class AnnotatedWildcardType extends AnnotatedType { /** * Returns the potentially annotated lower bounds of this wildcard type. * If no lower bound is explicitly declared, the lower bound is the * type of null. In this case, a zero length array is returned. * * @apiNote While to date a wildcard may have at most one lower * bound, callers of this method should be written to accommodate * multiple bounds. * * @return the potentially annotated lower bounds of this wildcard type or * an empty array if no lower bound is explicitly declared. * @see WildcardType#getLowerBounds() */ get annotatedLowerBounds(): AnnotatedType[]; /** * Returns the potentially annotated upper bounds of this wildcard type. * If no upper bound is explicitly declared, the upper bound is * unannotated `Object` * * @apiNote While to date a wildcard may have at most one upper * bound, callers of this method should be written to accommodate * multiple bounds. * * @return the potentially annotated upper bounds of this wildcard type * @see WildcardType#getUpperBounds() */ get annotatedUpperBounds(): AnnotatedType[]; /** * Returns the potentially annotated type that this type is a member of, if * this type represents a nested type. For example, if this type is * `@TA O.I`, return a representation of `@TA O`. * * Returns `null` for an `AnnotatedType` that is an instance * of `AnnotatedWildcardType`. * * @return `null` * * @since 9 */ get annotatedOwnerType(): AnnotatedType; } } declare module 'java.lang.ProcessBuilder.Redirect' { import { Enum } from 'java.lang'; /** * The type of a {@link Redirect}. */ export class Type extends Enum { /** * The type of {@link Redirect#PIPE Redirect.PIPE}. */ static readonly PIPE: Type; /** * The type of {@link Redirect#INHERIT Redirect.INHERIT}. */ static readonly INHERIT: Type; /** * The type of redirects returned from * {@link Redirect#from Redirect.from(File)}. */ static readonly READ: Type; /** * The type of redirects returned from * {@link Redirect#to Redirect.to(File)}. */ static readonly WRITE: Type; /** * The type of redirects returned from * {@link Redirect#appendTo Redirect.appendTo(File)}. */ static readonly APPEND: Type; static valueOf(name: string): Type; static values(): Type[]; } } declare module 'java.lang.Runtime' { import { Comparable } from 'java.lang'; import { Optional, List } from 'java.util'; /** * A representation of a version string for an implementation of the * Java SE Platform. A version string consists of a version number * optionally followed by pre-release and build information. * * Version numbers * * A version number, `$VNUM`, is a non-empty sequence of * elements separated by period characters (U+002E). An element is either * zero, or an unsigned integer numeral without leading zeros. The final * element in a version number must not be zero. When an element is * incremented, all subsequent elements are removed. The format is: * * * [1-9][0-9]*((\.0)*\.[1-9][0-9]*)* * * * The sequence may be of arbitrary length but the first four elements * are assigned specific meanings, as follows: * * * $FEATURE.$INTERIM.$UPDATE.$PATCH * * * * * `$FEATURE` — The * feature-release counter, incremented for every feature release * regardless of release content. Features may be added in a feature * release; they may also be removed, if advance notice was given at least * one feature release ahead of time. Incompatible changes may be made * when justified. * * `$INTERIM` — The * interim-release counter, incremented for non-feature releases that * contain compatible bug fixes and enhancements but no incompatible * changes, no feature removals, and no changes to standard APIs. * * * `$UPDATE` — The update-release * counter, incremented for compatible update releases that fix security * issues, regressions, and bugs in newer features. * * `$PATCH` — The emergency * patch-release counter, incremented only when it's necessary to produce * an emergency release to fix a critical issue. * * * * The fifth and later elements of a version number are free for use by * platform implementors, to identify implementor-specific patch * releases. * * A version number never has trailing zero elements. If an element * and all those that follow it logically have the value zero then all of * them are omitted. * * The sequence of numerals in a version number is compared to another * such sequence in numerical, pointwise fashion; e.g., ` * 10.0.4` is less than `10.1.2`. If one sequence is shorter than * another then the missing elements of the shorter sequence are considered * to be less than the corresponding elements of the longer sequence; * e.g., `10.0.2` is less than `10.0.2.1`. * * Version strings * * A version string, `$VSTR`, is a version number ` * $VNUM`, as described above, optionally followed by pre-release and build * information, in one of the following formats: * * * $VNUM(-$PRE)?\+$BUILD(-$OPT)? * $VNUM-$PRE(-$OPT)? * $VNUM(\+-$OPT)? * * * where: * * * * `$PRE`, matching `([a-zA-Z0-9]+)` * — A pre-release identifier. Typically `ea`, for a * potentially unstable early-access release under active development, or * `internal`, for an internal developer build. * * `$BUILD`, matching ` * (0|[1-9][0-9]*)` — The build number, incremented for each promoted * build. `$BUILD` is reset to `1` when any portion of ` * $VNUM` is incremented. * * `$OPT`, matching `([-a-zA-Z0-9.]+)` * — Additional build information, if desired. In the case of an * `internal` build this will often contain the date and time of the * build. * * * * A version string `10-ea` matches `$VNUM = "10"` and * `$PRE = "ea"`. The version string `10+-ea` matches * `$VNUM = "10"` and `$OPT = "ea"`. * * When comparing two version strings, the value of `$OPT`, if * present, may or may not be significant depending on the chosen * comparison method. The comparison methods {@link #compareTo(Version) * compareTo()} and {@link #compareToIgnoreOptional(Version) * compareToIgnoreOptional()} should be used consistently with the * corresponding methods {@link #equals(Object) equals()} and {@link * #equalsIgnoreOptional(Object) equalsIgnoreOptional()}. * * A short version string, `$SVSTR`, often useful in * less formal contexts, is a version number optionally followed by a * pre-release identifier: * * * $VNUM(-$PRE)? * * * This is a value-based * class; programmers should treat instances that are * {@linkplain #equals(Object) equal} as interchangeable and should not * use instances for synchronization, or unpredictable behavior may * occur. For example, in a future release, synchronization may fail. * * @since 9 */ export class Version extends Comparable { /** * Parses the given string as a valid * version string containing a * version number followed by pre-release and * build information. * * @param s * A string to interpret as a version * * @throws IllegalArgumentException * If the given string cannot be interpreted as a valid * version * * @throws NullPointerException * If the given string is `null` * * @throws NumberFormatException * If an element of the version number or the build number * cannot be represented as an {@link Integer} * * @return The Version of the given string */ static parse(s: string): Version; /** * Returns the value of the feature element of * the version number. * * @return The value of the feature element * * @since 10 */ feature(): number; /** * Returns the value of the interim element of * the version number, or zero if it is absent. * * @return The value of the interim element, or zero * * @since 10 */ interim(): number; /** * Returns the value of the update element of the * version number, or zero if it is absent. * * @return The value of the update element, or zero * * @since 10 */ update(): number; /** * Returns the value of the patch element of the * version number, or zero if it is absent. * * @return The value of the patch element, or zero * * @since 10 */ patch(): number; /** * Returns the value of the major element of the version number. * * @deprecated As of Java SE 10, the first element of a version * number is not the major-release number but the feature-release * counter, incremented for every time-based release. Use the {@link * #feature()} method in preference to this method. For compatibility, * this method returns the value of the feature * element. * * @return The value of the feature element */ major(): number; /** * Returns the value of the minor element of the version number, or * zero if it is absent. * * @deprecated As of Java SE 10, the second element of a version * number is not the minor-release number but the interim-release * counter, incremented for every interim release. Use the {@link * #interim()} method in preference to this method. For compatibility, * this method returns the value of the interim * element, or zero if it is absent. * * @return The value of the interim element, or zero */ minor(): number; /** * Returns the value of the security element of the version number, or * zero if it is absent. * * @deprecated As of Java SE 10, the third element of a version * number is not the security level but the update-release counter, * incremented for every update release. Use the {@link #update()} * method in preference to this method. For compatibility, this method * returns the value of the update element, or * zero if it is absent. * * @return The value of the update element, or zero */ security(): number; /** * Returns an unmodifiable {@link java.util.List List} of the integers * represented in the version number. * The `List` always contains at least one element corresponding to * the feature version number. * * @return An unmodifiable list of the integers * represented in the version number */ version(): number[]; /** * Returns the optional pre-release information. * * @return The optional pre-release information as a String */ pre(): Optional; /** * Returns the build number. * * @return The optional build number. */ build(): Optional; /** * Returns optional additional identifying build * information. * * @return Additional build information as a String */ optional(): Optional; /** * Compares this version to another. * * Each of the components in the version is * compared in the following order of precedence: version numbers, * pre-release identifiers, build numbers, optional build information. * * * Comparison begins by examining the sequence of version numbers. * If one sequence is shorter than another, then the missing elements * of the shorter sequence are considered to be less than the * corresponding elements of the longer sequence. * * A version with a pre-release identifier is always considered to * be less than a version without one. Pre-release identifiers are * compared numerically when they consist only of digits, and * lexicographically otherwise. Numeric identifiers are considered to * be less than non-numeric identifiers. * * A version without a build number is always less than one with a * build number; otherwise build numbers are compared numerically. * * The optional build information is compared lexicographically. * During this comparison, a version with optional build information is * considered to be greater than a version without one. * * @param obj * The object to be compared * * @return A negative integer, zero, or a positive integer if this * `Version` is less than, equal to, or greater than the * given `Version` * * @throws NullPointerException * If the given object is `null` */ compareTo(obj: Version): number; /** * Compares this version to another disregarding optional build * information. * * Two versions are compared by examining the version string as * described in {@link #compareTo(Version)} with the exception that the * optional build information is always ignored. * * This method provides ordering which is consistent with * `equalsIgnoreOptional()`. * * @param obj * The object to be compared * * @return A negative integer, zero, or a positive integer if this * `Version` is less than, equal to, or greater than the * given `Version` * * @throws NullPointerException * If the given object is `null` */ compareToIgnoreOptional(obj: Version): number; /** * Returns a string representation of this version. * * @return The version string */ toString(): string; /** * Determines whether this `Version` is equal to another object. * * Two `Version`s are equal if and only if they represent the * same version string. * * @param obj * The object to which this `Version` is to be compared * * @return `true` if, and only if, the given object is a ` * Version` that is identical to this `Version` * */ equals(obj: any): boolean; /** * Determines whether this `Version` is equal to another * disregarding optional build information. * * Two `Version`s are equal if and only if they represent the * same version string disregarding the optional build information. * * @param obj * The object to which this `Version` is to be compared * * @return `true` if, and only if, the given object is a ` * Version` that is identical to this `Version` * ignoring the optional build information * */ equalsIgnoreOptional(obj: any): boolean; /** * Returns the hash code of this version. * * @return The hashcode of this version */ hashCode(): number; } } declare module 'java.lang.invoke.MethodHandles' { import { Field, Constructor, Method } from 'java.lang.reflect'; import { ProtectionDomain } from 'java.security'; import { Class } from 'java.lang'; import { ClassOption } from 'java.lang.invoke.MethodHandles.Lookup'; import { ConcurrentHashMap } from 'java.util.concurrent'; import { MethodType, VarHandle, MemberName, MethodHandleInfo, DirectMethodHandle, MethodHandle } from 'java.lang.invoke'; /** * A lookup object is a factory for creating method handles, * when the creation requires access checking. * Method handles do not perform * access checks when they are called, but rather when they are created. * Therefore, method handle access * restrictions must be enforced when a method handle is created. * The caller class against which those restrictions are enforced * is known as the {@linkplain #lookupClass() lookup class}. * * A lookup class which needs to create method handles will call * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. * When the `Lookup` factory object is created, the identity of the lookup class is * determined, and securely stored in the `Lookup` object. * The lookup class (or its delegates) may then use factory methods * on the `Lookup` object to create method handles for access-checked members. * This includes all methods, constructors, and fields which are allowed to the lookup class, * even private ones. * * Lookup Factory Methods * The factory methods on a `Lookup` object correspond to all major * use cases for methods, constructors, and fields. * Each method handle created by a factory method is the functional * equivalent of a particular bytecode behavior. * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of * the Java Virtual Machine Specification.) * Here is a summary of the correspondence between these factory methods and * the behavior of the resulting method handles: * * lookup method behaviors * * * lookup expression * member * bytecode behavior * * * * * {@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)} * `FT f;``(T) this.f;` * * * {@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)} * `static``FT f;``(FT) C.f;` * * * {@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)} * `FT f;``this.f = x;` * * * {@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)} * `static``FT f;``C.f = arg;` * * * {@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)} * `T m(A*);``(T) this.m(arg*);` * * * {@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)} * `static``T m(A*);``(T) C.m(arg*);` * * * {@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)} * `T m(A*);``(T) super.m(arg*);` * * * {@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)} * `C(A*);``new C(arg*);` * * * {@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)} * (`static`)?`FT f;``(FT) aField.get(thisOrNull);` * * * {@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)} * (`static`)?`FT f;``aField.set(thisOrNull, arg);` * * * {@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)} * (`static`)?`T m(A*);``(T) aMethod.invoke(thisOrNull, arg*);` * * * {@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)} * `C(A*);``(C) aConstructor.newInstance(arg*);` * * * {@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)} * `T m(A*);``(T) super.m(arg*);` * * * {@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")} * `class C { ... `}`C.class;` * * * * * Here, the type `C` is the class or interface being searched for a member, * documented as a parameter named `refc` in the lookup methods. * The method type `MT` is composed from the return type `T` * and the sequence of argument types `A*`. * The constructor also has a sequence of argument types `A*` and * is deemed to return the newly-created object of type `C`. * Both `MT` and the field type `FT` are documented as a parameter named `type`. * The formal parameter `this` stands for the self-reference of type `C`; * if it is present, it is always the leading argument to the method handle invocation. * (In the case of some `protected` members, `this` may be * restricted in type to the lookup class; see below.) * The name `arg` stands for all the other method handle arguments. * In the code examples for the Core Reflection API, the name `thisOrNull` * stands for a null reference if the accessed method or field is static, * and `this` otherwise. * The names `aMethod`, `aField`, and `aConstructor` stand * for reflective objects corresponding to the given members declared in type `C`. * * The bytecode behavior for a `findClass` operation is a load of a constant class, * as if by `ldc CONSTANT_Class`. * The behavior is represented, not as a method handle, but directly as a `Class` constant. * * In cases where the given member is of variable arity (i.e., a method or constructor) * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. * In all other cases, the returned method handle will be of fixed arity. * * Discussion: * The equivalence between looked-up method handles and underlying * class members and bytecode behaviors * can break down in a few ways: * * If `C` is not symbolically accessible from the lookup class's loader, * the lookup can still succeed, even when there is no equivalent * Java expression or bytecoded constant. * Likewise, if `T` or `MT` * is not symbolically accessible from the lookup class's loader, * the lookup can still succeed. * For example, lookups for `MethodHandle.invokeExact` and * `MethodHandle.invoke` will always succeed, regardless of requested type. * If there is a security manager installed, it can forbid the lookup * on various grounds (see below). * By contrast, the `ldc` instruction on a `CONSTANT_MethodHandle` * constant is not subject to security manager checks. * If the looked-up method has a * very large arity, * the method handle creation may fail with an * `IllegalArgumentException`, due to the method handle type having * too many parameters. * * * Access checking * Access checks are applied in the factory methods of `Lookup`, * when a method handle is created. * This is a key difference from the Core Reflection API, since * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} * performs access checking against every caller, on every call. * * All access checks start from a `Lookup` object, which * compares its recorded lookup class against all requests to * create method handles. * A single `Lookup` object can be used to create any number * of access-checked method handles, all checked against a single * lookup class. * * A `Lookup` object can be shared with other trusted code, * such as a metaobject protocol. * A shared `Lookup` object delegates the capability * to create method handles on private members of the lookup class. * Even if privileged code uses the `Lookup` object, * the access checking is confined to the privileges of the * original lookup class. * * A lookup can fail, because * the containing class is not accessible to the lookup class, or * because the desired class member is missing, or because the * desired class member is not accessible to the lookup class, or * because the lookup object is not trusted enough to access the member. * In the case of a field setter function on a `final` field, * finality enforcement is treated as a kind of access control, * and the lookup will fail, except in special cases of * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. * In any of these cases, a `ReflectiveOperationException` will be * thrown from the attempted lookup. The exact class will be one of * the following: * * NoSuchMethodException — if a method is requested but does not exist * NoSuchFieldException — if a field is requested but does not exist * IllegalAccessException — if the member exists but an access check fails * * * In general, the conditions under which a method handle may be * looked up for a method `M` are no more restrictive than the conditions * under which the lookup class could have compiled, verified, and resolved a call to `M`. * Where the JVM would raise exceptions like `NoSuchMethodError`, * a method handle lookup will generally raise a corresponding * checked exception, such as `NoSuchMethodException`. * And the effect of invoking the method handle resulting from the lookup * is exactly equivalent * to executing the compiled, verified, and resolved call to `M`. * The same point is true of fields and constructors. * * Discussion: * Access checks only apply to named and reflected methods, * constructors, and fields. * Other method handle creation methods, such as * {@link MethodHandle#asType MethodHandle.asType}, * do not require any access checks, and are used * independently of any `Lookup` object. * * If the desired member is `protected`, the usual JVM rules apply, * including the requirement that the lookup class must either be in the * same package as the desired member, or must inherit that member. * (See the Java Virtual Machine Specification, sections {@jvms * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) * In addition, if the desired member is a non-static field or method * in a different package, the resulting method handle may only be applied * to objects of the lookup class or one of its subclasses. * This requirement is enforced by narrowing the type of the leading * `this` parameter from `C` * (which will necessarily be a superclass of the lookup class) * to the lookup class itself. * * The JVM imposes a similar requirement on `invokespecial` instruction, * that the receiver argument must match both the resolved method and * the current class. Again, this requirement is enforced by narrowing the * type of the leading parameter to the resulting method handle. * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) * * The JVM represents constructors and static initializer blocks as internal methods * with special names (`""` and `""`). * The internal syntax of invocation instructions allows them to refer to such internal * methods as if they were normal methods, but the JVM bytecode verifier rejects them. * A lookup of such an internal method will produce a `NoSuchMethodException`. * * If the relationship between nested types is expressed directly through the * `NestHost` and `NestMembers` attributes * (see the Java Virtual Machine Specification, sections {@jvms * 4.7.28} and {@jvms 4.7.29}), * then the associated `Lookup` object provides direct access to * the lookup class and all of its nestmates * (see {@link java.lang.Class#getNestHost Class.getNestHost}). * Otherwise, access between nested classes is obtained by the Java compiler creating * a wrapper method to access a private method of another class in the same nest. * For example, a nested class `C.D` * can access private members within other related classes such as * `C`, `C.D.E`, or `C.B`, * but the Java compiler may need to generate wrapper methods in * those related classes. In such cases, a `Lookup` object on * `C.E` would be unable to access those private members. * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, * which can transform a lookup on `C.E` into one on any of those other * classes, without special elevation of privilege. * * The accesses permitted to a given lookup object may be limited, * according to its set of {@link #lookupModes lookupModes}, * to a subset of members normally accessible to the lookup class. * For example, the {@link MethodHandles#publicLookup publicLookup} * method produces a lookup object which is only allowed to access * public members in public classes of exported packages. * The caller sensitive method {@link MethodHandles#lookup lookup} * produces a lookup object with full capabilities relative to * its caller class, to emulate all supported bytecode behaviors. * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object * with fewer access modes than the original lookup object. * * * * Discussion of private and module access: * We say that a lookup has private access * if its {@linkplain #lookupModes lookup modes} * include the possibility of accessing `private` members * (which includes the private members of nestmates). * As documented in the relevant methods elsewhere, * only lookups with private access possess the following capabilities: * * access private fields, methods, and constructors of the lookup class and its nestmates * create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions * avoid package access checks * for classes accessible to the lookup class * create {@link Lookup#in delegated lookup objects} which have private access to other classes * within the same package member * * * Similarly, a lookup with module access ensures that the original lookup creator was * a member in the same module as the lookup class. * * Private and module access are independently determined modes; a lookup may have * either or both or neither. A lookup which possesses both access modes is said to * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. * * A lookup with original access ensures that this lookup is created by * the original lookup class and the bootstrap method invoked by the VM. * Such a lookup with original access also has private and module access * which has the following additional capability: * * create method handles which invoke caller sensitive methods, * such as `Class.forName` * obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) * class data} associated with the lookup class * * * Each of these permissions is a consequence of the fact that a lookup object * with private access can be securely traced back to an originating class, * whose bytecode behaviors and Java language access permissions * can be reliably determined and emulated by method handles. * * Cross-module lookups * When a lookup class in one module `M1` accesses a class in another module * `M2`, extra access checking is performed beyond the access mode bits. * A `Lookup` with {@link #PUBLIC} mode and a lookup class in `M1` * can access public types in `M2` when `M2` is readable to `M1` * and when the type is in a package of `M2` that is exported to * at least `M1`. * * A `Lookup` on `C` can also teleport to a target class * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) * MethodHandles.privateLookupIn} methods. * Teleporting across modules will always record the original lookup class as * the {@linkplain #previousLookupClass() previous lookup class} * and drops {@link Lookup#MODULE MODULE} access. * If the target class is in the same module as the lookup class `C`, * then the target class becomes the new lookup class * and there is no change to the previous lookup class. * If the target class is in a different module from `M1` (`C`'s module), * `C` becomes the new previous lookup class * and the target class becomes the new lookup class. * In that case, if there was already a previous lookup class in `M0`, * and it differs from `M1` and `M2`, then the resulting lookup * drops all privileges. * For example, * * {@code * Lookup lookup = MethodHandles.lookup(); // in class C * Lookup lookup2 = lookup.in(D.class); * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); * } * * The {@link #lookup()} factory method produces a `Lookup` object * with `null` previous lookup class. * {@link Lookup#in lookup.in(D.class)} transforms the `lookup` on class `C` * to class `D` without elevation of privileges. * If `C` and `D` are in the same module, * `lookup2` records `D` as the new lookup class and keeps the * same previous lookup class as the original `lookup`, or * `null` if not present. * * When a `Lookup` teleports from a class * in one nest to another nest, `PRIVATE` access is dropped. * When a `Lookup` teleports from a class in one package to * another package, `PACKAGE` access is dropped. * When a `Lookup` teleports from a class in one module to another module, * `MODULE` access is dropped. * Teleporting across modules drops the ability to access non-exported classes * in both the module of the new lookup class and the module of the old lookup class * and the resulting `Lookup` remains only `PUBLIC` access. * A `Lookup` can teleport back and forth to a class in the module of * the lookup class and the module of the previous class lookup. * Teleporting across modules can only decrease access but cannot increase it. * Teleporting to some third module drops all accesses. * * In the above example, if `C` and `D` are in different modules, * `lookup2` records `D` as its lookup class and * `C` as its previous lookup class and `lookup2` has only * `PUBLIC` access. `lookup2` can teleport to other class in * `C`'s module and `D`'s module. * If class `E` is in a third module, `lookup2.in(E.class)` creates * a `Lookup` on `E` with no access and `lookup2`'s lookup * class `D` is recorded as its previous lookup class. * * Teleporting across modules restricts access to the public types that * both the lookup class and the previous lookup class can equally access * (see below). * * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} * can be used to teleport a `lookup` from class `C` to class `T` * and create a new `Lookup` with private access * if the lookup class is allowed to do deep reflection on `T`. * The `lookup` must have {@link #MODULE} and {@link #PRIVATE} access * to call `privateLookupIn`. * A `lookup` on `C` in module `M1` is allowed to do deep reflection * on all classes in `M1`. If `T` is in `M1`, `privateLookupIn` * produces a new `Lookup` on `T` with full capabilities. * A `lookup` on `C` is also allowed * to do deep reflection on `T` in another module `M2` if * `M1` reads `M2` and `M2` {@link Module#isOpen(String,Module) opens} * the package containing `T` to at least `M1`. * `T` becomes the new lookup class and `C` becomes the new previous * lookup class and `MODULE` access is dropped from the resulting `Lookup`. * The resulting `Lookup` can be used to do member lookup or teleport * to another lookup class by calling {@link #in Lookup::in}. But * it cannot be used to obtain another private `Lookup` by calling * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} * because it has no `MODULE` access. * * Cross-module access checks * * A `Lookup` with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode * allows cross-module access. The access checking is performed with respect * to both the lookup class and the previous lookup class if present. * * A `Lookup` with {@link #UNCONDITIONAL} mode can access public type * in all modules when the type is in a package that is {@linkplain Module#isExported(String) * exported unconditionally}. * * If a `Lookup` on `LC` in `M1` has no previous lookup class, * the lookup with {@link #PUBLIC} mode can access all public types in modules * that are readable to `M1` and the type is in a package that is exported * at least to `M1`. * * If a `Lookup` on `LC` in `M1` has a previous lookup class * `PLC` on `M0`, the lookup with {@link #PUBLIC} mode can access * the intersection of all public types that are accessible to `M1` * with all public types that are accessible to `M0`. `M0` * reads `M1` and hence the set of accessible types includes: * * * * Public types in the following packages are accessible to the * lookup class and the previous lookup class. * * * * Equally accessible types to `M0` and `M1` * * * * * unconditional-exported packages from `M1` * * * unconditional-exported packages from `M0` if `M1` reads `M0` * * * unconditional-exported packages from a third module `M2` * if both `M0` and `M1` read `M2` * * * qualified-exported packages from `M1` to `M0` * * * qualified-exported packages from `M0` to `M1` * if `M1` reads `M0` * * * qualified-exported packages from a third module `M2` to * both `M0` and `M1` if both `M0` and `M1` read `M2` * * * * * Access modes * * The table below shows the access modes of a `Lookup` produced by * any of the following factory or transformation methods: * * {@link #lookup() MethodHandles::lookup} * {@link #publicLookup() MethodHandles::publicLookup} * {@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn} * {@link Lookup#in Lookup::in} * {@link Lookup#dropLookupMode(int) Lookup::dropLookupMode} * * * * * Access mode summary * * * * Lookup object * original * protected * private * package * module * public * * * * * `CL = MethodHandles.lookup()` in `C` * ORI * PRO * PRI * PAC * MOD * 1R * * * `CL.in(C1)` same package * * * * PAC * MOD * 1R * * * `CL.in(C1)` same module * * * * * MOD * 1R * * * `CL.in(D)` different module * * * * * * 2R * * * `CL.in(D).in(C)` hop back to module * * * * * * 2R * * * `PRI1 = privateLookupIn(C1,CL)` * * PRO * PRI * PAC * MOD * 1R * * * `PRI1a = privateLookupIn(C,PRI1)` * * PRO * PRI * PAC * MOD * 1R * * * `PRI1.in(C1)` same package * * * * PAC * MOD * 1R * * * `PRI1.in(C1)` different package * * * * * MOD * 1R * * * `PRI1.in(D)` different module * * * * * * 2R * * * `PRI1.dropLookupMode(PROTECTED)` * * * PRI * PAC * MOD * 1R * * * `PRI1.dropLookupMode(PRIVATE)` * * * * PAC * MOD * 1R * * * `PRI1.dropLookupMode(PACKAGE)` * * * * * MOD * 1R * * * `PRI1.dropLookupMode(MODULE)` * * * * * * 1R * * * `PRI1.dropLookupMode(PUBLIC)` * * * * * * none * * `PRI2 = privateLookupIn(D,CL)` * * PRO * PRI * PAC * * 2R * * * `privateLookupIn(D,PRI1)` * * PRO * PRI * PAC * * 2R * * * `privateLookupIn(C,PRI2)` fails * * * * * * IAE * * * `PRI2.in(D2)` same package * * * * PAC * * 2R * * * `PRI2.in(D2)` different package * * * * * * 2R * * * `PRI2.in(C1)` hop back to module * * * * * * 2R * * * `PRI2.in(E)` hop to third module * * * * * * none * * * `PRI2.dropLookupMode(PROTECTED)` * * * PRI * PAC * * 2R * * * `PRI2.dropLookupMode(PRIVATE)` * * * * PAC * * 2R * * * `PRI2.dropLookupMode(PACKAGE)` * * * * * * 2R * * * `PRI2.dropLookupMode(MODULE)` * * * * * * 2R * * * `PRI2.dropLookupMode(PUBLIC)` * * * * * * none * * * `CL.dropLookupMode(PROTECTED)` * * * PRI * PAC * MOD * 1R * * * `CL.dropLookupMode(PRIVATE)` * * * * PAC * MOD * 1R * * * `CL.dropLookupMode(PACKAGE)` * * * * * MOD * 1R * * * `CL.dropLookupMode(MODULE)` * * * * * * 1R * * * `CL.dropLookupMode(PUBLIC)` * * * * * * none * * * `PUB = publicLookup()` * * * * * * U * * * `PUB.in(D)` different module * * * * * * U * * * `PUB.in(D).in(E)` third module * * * * * * U * * * `PUB.dropLookupMode(UNCONDITIONAL)` * * * * * * none * * * `privateLookupIn(C1,PUB)` fails * * * * * * IAE * * * `ANY.in(X)`, for inaccessible `X` * * * * * * none * * * * * * Notes: * * Class `C` and class `C1` are in module `M1`, * but `D` and `D2` are in module `M2`, and `E` * is in module `M3`. `X` stands for class which is inaccessible * to the lookup. `ANY` stands for any of the example lookups. * `ORI` indicates {@link #ORIGINAL} bit set, * `PRO` indicates {@link #PROTECTED} bit set, * `PRI` indicates {@link #PRIVATE} bit set, * `PAC` indicates {@link #PACKAGE} bit set, * `MOD` indicates {@link #MODULE} bit set, * `1R` and `2R` indicate {@link #PUBLIC} bit set, * `U` indicates {@link #UNCONDITIONAL} bit set, * `IAE` indicates `IllegalAccessException` thrown. * Public access comes in three kinds: * * unconditional (`U`): the lookup assumes readability. * The lookup has `null` previous lookup class. * one-module-reads (`1R`): the module access checking is * performed with respect to the lookup class. The lookup has `null` * previous lookup class. * two-module-reads (`2R`): the module access checking is * performed with respect to the lookup class and the previous lookup class. * The lookup has a non-null previous lookup class which is in a * different module from the current lookup class. * * Any attempt to reach a third module loses all access. * If a target class `X` is not accessible to `Lookup::in` * all access modes are dropped. * * * Security manager interactions * Although bytecode instructions can only refer to classes in * a related class loader, this API can search for methods in any * class, as long as a reference to its `Class` object is * available. Such cross-loader references are also possible with the * Core Reflection API, and are impossible to bytecode instructions * such as `invokestatic` or `getfield`. * There is a {@linkplain java.lang.SecurityManager security manager API} * to allow applications to check such cross-loader references. * These checks apply to both the `MethodHandles.Lookup` API * and the Core Reflection API * (as found on {@link java.lang.Class Class}). * * If a security manager is present, member and class lookups are subject to * additional checks. * From one to three calls are made to the security manager. * Any of these calls can refuse access by throwing a * {@link java.lang.SecurityException SecurityException}. * Define `smgr` as the security manager, * `lookc` as the lookup class of the current lookup object, * `refc` as the containing class in which the member * is being sought, and `defc` as the class in which the * member is actually defined. * (If a class or other type is being accessed, * the `refc` and `defc` values are the class itself.) * The value `lookc` is defined as not present * if the current lookup object does not have * {@linkplain #hasFullPrivilegeAccess() full privilege access}. * The calls are made according to the following rules: * * Step 1: * If `lookc` is not present, or if its class loader is not * the same as or an ancestor of the class loader of `refc`, * then {@link SecurityManager#checkPackageAccess * smgr.checkPackageAccess(refcPkg)} is called, * where `refcPkg` is the package of `refc`. * Step 2a: * If the retrieved member is not public and * `lookc` is not present, then * {@link SecurityManager#checkPermission smgr.checkPermission} * with `RuntimePermission("accessDeclaredMembers")` is called. * Step 2b: * If the retrieved class has a `null` class loader, * and `lookc` is not present, then * {@link SecurityManager#checkPermission smgr.checkPermission} * with `RuntimePermission("getClassLoader")` is called. * Step 3: * If the retrieved member is not public, * and if `lookc` is not present, * and if `defc` and `refc` are different, * then {@link SecurityManager#checkPackageAccess * smgr.checkPackageAccess(defcPkg)} is called, * where `defcPkg` is the package of `defc`. * * Security checks are performed after other access checks have passed. * Therefore, the above rules presuppose a member or class that is public, * or else that is being accessed from a lookup class that has * rights to access the member or class. * * If a security manager is present and the current lookup object does not have * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then * {@link #defineClass(byte[]) defineClass}, * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass}, * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...) * defineHiddenClassWithClassData} * calls {@link SecurityManager#checkPermission smgr.checkPermission} * with `RuntimePermission("defineClass")`. * * Caller sensitive methods * A small number of Java methods have a special property called caller sensitivity. * A caller-sensitive method can behave differently depending on the * identity of its immediate caller. * * If a method handle for a caller-sensitive method is requested, * the general rules for bytecode behaviors apply, * but they take account of the lookup class in a special way. * The resulting method handle behaves as if it were called * from an instruction contained in the lookup class, * so that the caller-sensitive method detects the lookup class. * (By contrast, the invoker of the method handle is disregarded.) * Thus, in the case of caller-sensitive methods, * different lookup classes may give rise to * differently behaving method handles. * * In cases where the lookup object is * {@link MethodHandles#publicLookup() publicLookup()}, * or some other lookup object without the * {@linkplain #ORIGINAL original access}, * the lookup class is disregarded. * In such cases, no caller-sensitive method handle can be created, * access is forbidden, and the lookup fails with an * `IllegalAccessException`. * * Discussion: * For example, the caller-sensitive method * {@link java.lang.Class#forName(String) Class.forName(x)} * can return varying classes or throw varying exceptions, * depending on the class loader of the class that calls it. * A public lookup of `Class.forName` will fail, because * there is no reasonable way to determine its bytecode behavior. * * If an application caches method handles for broad sharing, * it should use `publicLookup()` to create them. * If there is a lookup of `Class.forName`, it will fail, * and the application must take appropriate action in that case. * It may be that a later lookup, perhaps during the invocation of a * bootstrap method, can incorporate the specific identity * of the caller, making the method accessible. * * The function `MethodHandles.lookup` is caller sensitive * so that there can be a secure foundation for lookups. * Nearly all other methods in the JSR 292 API rely on lookup * objects to check access requests. * * @revised 9 */ export class Lookup { /** A single-bit mask representing `public` access, * which may contribute to the result of {@link #lookupModes lookupModes}. * The value, `0x01`, happens to be the same as the value of the * `public` {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. * * A `Lookup` with this lookup mode performs cross-module access check * with respect to the {@linkplain #lookupClass() lookup class} and * {@linkplain #previousLookupClass() previous lookup class} if present. */ static readonly PUBLIC: number; /** A single-bit mask representing `private` access, * which may contribute to the result of {@link #lookupModes lookupModes}. * The value, `0x02`, happens to be the same as the value of the * `private` {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. */ static readonly PRIVATE: number; /** A single-bit mask representing `protected` access, * which may contribute to the result of {@link #lookupModes lookupModes}. * The value, `0x04`, happens to be the same as the value of the * `protected` {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. */ static readonly PROTECTED: number; /** A single-bit mask representing `package` access (default access), * which may contribute to the result of {@link #lookupModes lookupModes}. * The value is `0x08`, which does not correspond meaningfully to * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. */ static readonly PACKAGE: number; /** A single-bit mask representing `module` access, * which may contribute to the result of {@link #lookupModes lookupModes}. * The value is `0x10`, which does not correspond meaningfully to * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. * In conjunction with the `PUBLIC` modifier bit, a `Lookup` * with this lookup mode can access all public types in the module of the * lookup class and public types in packages exported by other modules * to the module of the lookup class. * * If this lookup mode is set, the {@linkplain #previousLookupClass() * previous lookup class} is always `null`. * * @since 9 */ static readonly MODULE: number; /** A single-bit mask representing `unconditional` access * which may contribute to the result of {@link #lookupModes lookupModes}. * The value is `0x20`, which does not correspond meaningfully to * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. * A `Lookup` with this lookup mode assumes {@linkplain * java.lang.Module#canRead(java.lang.Module) readability}. * This lookup mode can access all public members of public types * of all modules when the type is in a package that is {@link * java.lang.Module#isExported(String) exported unconditionally}. * * * If this lookup mode is set, the {@linkplain #previousLookupClass() * previous lookup class} is always `null`. * * @since 9 * @see #publicLookup() */ static readonly UNCONDITIONAL: number; /** A single-bit mask representing `original` access * which may contribute to the result of {@link #lookupModes lookupModes}. * The value is `0x40`, which does not correspond meaningfully to * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. * * * If this lookup mode is set, the `Lookup` object must be * created by the original lookup class by calling * {@link MethodHandles#lookup()} method or by a bootstrap method * invoked by the VM. The `Lookup` object with this lookup * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. * * @since 16 */ static readonly ORIGINAL: number; /** Tells which class is performing the lookup. It is this class against * which checks are performed for visibility and access permissions. * * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, * access checks are performed against both the lookup class and the previous lookup class. * * The class implies a maximum level of access permission, * but the permissions may be additionally limited by the bitmask * {@link #lookupModes lookupModes}, which controls whether non-public members * can be accessed. * @return the lookup class, on behalf of which this lookup object finds members * @see Cross-module lookups */ lookupClass(): Class; /** Reports a lookup class in another module that this lookup object * was previously teleported from, or `null`. * * A `Lookup` object produced by the factory methods, such as the * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, * has `null` previous lookup class. * A `Lookup` object has a non-null previous lookup class * when this lookup was teleported from an old lookup class * in one module to a new lookup class in another module. * * @return the lookup class in another module that this lookup object was * previously teleported from, or `null` * @since 14 * @see #in(Class) * @see MethodHandles#privateLookupIn(Class, Lookup) * @see Cross-module lookups */ previousLookupClass(): Class; /** Tells which access-protection classes of members this lookup object can produce. * The result is a bit-mask of the bits * {@linkplain #PUBLIC PUBLIC (0x01)}, * {@linkplain #PRIVATE PRIVATE (0x02)}, * {@linkplain #PROTECTED PROTECTED (0x04)}, * {@linkplain #PACKAGE PACKAGE (0x08)}, * {@linkplain #MODULE MODULE (0x10)}, * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. * * A freshly-created lookup object * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has * all possible bits set, except `UNCONDITIONAL`. * A lookup object on a new lookup class * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} * may have some mode bits set to zero. * Mode bits can also be * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. * Once cleared, mode bits cannot be restored from the downgraded lookup object. * The purpose of this is to restrict access via the new lookup object, * so that it can access only names which can be reached by the original * lookup object, and also by the new lookup class. * @return the lookup modes, which limit the kinds of access performed by this lookup object * @see #in * @see #dropLookupMode * * @revised 9 */ lookupModes(): number; /** * Creates a lookup on the specified new lookup class. * The resulting object will report the specified * class as its own {@link #lookupClass() lookupClass}. * * * However, the resulting `Lookup` object is guaranteed * to have no more access capabilities than the original. * In particular, access capabilities can be lost as follows: * If the new lookup class is different from the old lookup class, * i.e. {@link #ORIGINAL ORIGINAL} access is lost. * If the new lookup class is in a different module from the old one, * i.e. {@link #MODULE MODULE} access is lost. * If the new lookup class is in a different package * than the old one, protected and default (package) members will not be accessible, * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. * If the new lookup class is not within the same package member * as the old one, private members will not be accessible, and protected members * will not be accessible by virtue of inheritance, * i.e. {@link #PRIVATE PRIVATE} access is lost. * (Protected members may continue to be accessible because of package sharing.) * If the new lookup class is not * {@linkplain #accessClass(Class) accessible} to this lookup, * then no members, not even public members, will be accessible * i.e. all access modes are lost. * If the new lookup class, the old lookup class and the previous lookup class * are all in different modules i.e. teleporting to a third module, * all access modes are lost. * * * The new previous lookup class is chosen as follows: * * If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, * the new previous lookup class is `null`. * If the new lookup class is in the same module as the old lookup class, * the new previous lookup class is the old previous lookup class. * If the new lookup class is in a different module from the old lookup class, * the new previous lookup class is the old lookup class. * * * The resulting lookup's capabilities for loading classes * (used during {@link #findClass} invocations) * are determined by the lookup class' loader, * which may change due to this operation. * * @param requestedLookupClass the desired lookup class for the new lookup object * @return a lookup object which reports the desired lookup class, or the same object * if there is no change * @throws IllegalArgumentException if `requestedLookupClass` is a primitive type or void or array class * @throws NullPointerException if the argument is null * * @revised 9 * @see #accessClass(Class) * @see Cross-module lookups */ in(requestedLookupClass: Class): Lookup; /** * Creates a lookup on the same lookup class which this lookup object * finds members, but with a lookup mode that has lost the given lookup mode. * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or * {@link #UNCONDITIONAL UNCONDITIONAL}. * * If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, * this lookup has `UNCONDITIONAL` mode set and it has no other mode set. * When dropping `UNCONDITIONAL` on a public lookup then the resulting * lookup has no access. * * If this lookup is not a public lookup, then the following applies * regardless of its {@linkplain #lookupModes() lookup modes}. * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always * dropped and so the resulting lookup mode will never have these access * capabilities. When dropping `PACKAGE` * then the resulting lookup will not have `PACKAGE` or `PRIVATE` * access. When dropping `MODULE` then the resulting lookup will not * have `MODULE`, `PACKAGE`, or `PRIVATE` access. * When dropping `PUBLIC` then the resulting lookup has no access. * * @apiNote * A lookup with `PACKAGE` but not `PRIVATE` mode can safely * delegate non-public access within the package of the lookup class without * conferring private access. * A lookup with `MODULE` but not * `PACKAGE` mode can safely delegate `PUBLIC` access within * the module of the lookup class without conferring package access. * A lookup with a {@linkplain #previousLookupClass() previous lookup class} * (and `PUBLIC` but not `MODULE` mode) can safely delegate access * to public classes accessible to both the module of the lookup class * and the module of the previous lookup class. * * @param modeToDrop the lookup mode to drop * @return a lookup object which lacks the indicated mode, or the same object if there is no change * @throws IllegalArgumentException if `modeToDrop` is not one of `PUBLIC`, * `MODULE`, `PACKAGE`, `PROTECTED`, `PRIVATE`, `ORIGINAL` * or `UNCONDITIONAL` * @see MethodHandles#privateLookupIn * @since 9 */ dropLookupMode(modeToDrop: number): Lookup; /** * Creates and links a class or interface from `bytes` * with the same class loader and in the same runtime package and * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's * {@linkplain #lookupClass() lookup class} as if calling * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) * ClassLoader::defineClass}. * * The {@linkplain #lookupModes() lookup modes} for this lookup must include * {@link #PACKAGE PACKAGE} access as default (package) members will be * accessible to the class. The `PACKAGE` lookup mode serves to authenticate * that the lookup object was created by a caller in the runtime package (or derived * from a lookup originally created by suitably privileged code to a target class in * the runtime package). * * The `bytes` parameter is the class bytes of a valid class file (as defined * by the The Java Virtual Machine Specification) with a class name in the * same package as the lookup class. * * This method does not run the class initializer. The class initializer may * run at a later time, as detailed in section 12.4 of the The Java Language * Specification. * * If there is a security manager and this lookup does not have {@linkplain * #hasFullPrivilegeAccess() full privilege access}, its `checkPermission` method * is first called to check `RuntimePermission("defineClass")`. * * @param bytes the class bytes * @return the `Class` object for the class * @throws IllegalAccessException if this lookup does not have `PACKAGE` access * @throws ClassFormatError if `bytes` is not a `ClassFile` structure * @throws IllegalArgumentException if `bytes` denotes a class in a different package * than the lookup class or `bytes` is not a class or interface * (`ACC_MODULE` flag is set in the value of the `access_flags` item) * @throws VerifyError if the newly created class cannot be verified * @throws LinkageError if the newly created class cannot be linked for any other reason * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if `bytes` is `null` * @since 9 * @see Lookup#privateLookupIn * @see Lookup#dropLookupMode * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) */ defineClass(bytes: number[]): Class; /** * Creates a hidden class or interface from `bytes`, * returning a `Lookup` on the newly created class or interface. * * Ordinarily, a class or interface `C` is created by a class loader, * which either defines `C` directly or delegates to another class loader. * A class loader defines `C` directly by invoking * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) * ClassLoader::defineClass}, which causes the Java Virtual Machine * to derive `C` from a purported representation in `class` file format. * In situations where use of a class loader is undesirable, a class or interface * `C` can be created by this method instead. This method is capable of * defining `C`, and thereby creating it, without invoking * `ClassLoader::defineClass`. * Instead, this method defines `C` as if by arranging for * the Java Virtual Machine to derive a nonarray class or interface `C` * from a purported representation in `class` file format * using the following rules: * * * The {@linkplain #lookupModes() lookup modes} for this `Lookup` * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. * This level of access is needed to create `C` in the module * of the lookup class of this `Lookup`. * * The purported representation in `bytes` must be a `ClassFile` * structure of a supported major and minor version. The major and minor version * may differ from the `class` file version of the lookup class of this * `Lookup`. * * The value of `this_class` must be a valid index in the * `constant_pool` table, and the entry at that index must be a valid * `CONSTANT_Class_info` structure. Let `N` be the binary name * encoded in internal form that is specified by this structure. `N` must * denote a class or interface in the same package as the lookup class. * * Let `CN` be the string `N + "." + `, * where `` is an unqualified name. * * Let `newBytes` be the `ClassFile` structure given by * `bytes` with an additional entry in the `constant_pool` table, * indicating a `CONSTANT_Utf8_info` structure for `CN`, and * where the `CONSTANT_Class_info` structure indicated by `this_class` * refers to the new `CONSTANT_Utf8_info` structure. * * Let `L` be the defining class loader of the lookup class of this `Lookup`. * * `C` is derived with name `CN`, class loader `L`, and * purported representation `newBytes` as if by the rules of JVMS {@jvms 5.3.5}, * with the following adjustments: * * The constant indicated by `this_class` is permitted to specify a name * that includes a single `"."` character, even though this is not a valid * binary class or interface name in internal form. * * The Java Virtual Machine marks `L` as the defining class loader of `C`, * but no class loader is recorded as an initiating class loader of `C`. * * `C` is considered to have the same runtime * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} * and {@linkplain java.security.ProtectionDomain protection domain} * as the lookup class of this `Lookup`. * Let `GN` be the binary name obtained by taking `N` * (a binary name encoded in internal form) and replacing ASCII forward slashes with * ASCII periods. For the instance of {@link java.lang.Class} representing `C`: * * {@link Class#getName()} returns the string `GN + "/" + `, * even though this is not a valid binary class or interface name. * {@link Class#descriptorString()} returns the string * `"L" + N + "." + + ";"`, * even though this is not a valid type descriptor name. * {@link Class#describeConstable()} returns an empty optional as `C` * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}. * * * * * * After `C` is derived, it is linked by the Java Virtual Machine. * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: * * During verification, whenever it is necessary to load the class named * `CN`, the attempt succeeds, producing class `C`. No request is * made of any class loader. * * On any attempt to resolve the entry in the run-time constant pool indicated * by `this_class`, the symbolic reference is considered to be resolved to * `C` and resolution always succeeds immediately. * * * If the `initialize` parameter is `true`, * then `C` is initialized by the Java Virtual Machine. * * The newly created class or interface `C` serves as the * {@linkplain #lookupClass() lookup class} of the `Lookup` object * returned by this method. `C` is hidden in the sense that * no other class or interface can refer to `C` via a constant pool entry. * That is, a hidden class or interface cannot be named as a supertype, a field type, * a method parameter type, or a method return type by any other class. * This is because a hidden class or interface does not have a binary name, so * there is no internal form available to record in any class's constant pool. * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class) * modifiable} by Java agents or tool agents using the * JVM Tool Interface. * * A class or interface created by * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) * a class loader} has a strong relationship with that class loader. * That is, every `Class` object contains a reference to the `ClassLoader` * that {@linkplain Class#getClassLoader() defined it}. * This means that a class created by a class loader may be unloaded if and * only if its defining loader is not reachable and thus may be reclaimed * by a garbage collector (JLS 12.7). * * By default, however, a hidden class or interface may be unloaded even if * the class loader that is marked as its defining loader is * reachable. * This behavior is useful when a hidden class or interface serves multiple * classes defined by arbitrary class loaders. In other cases, a hidden * class or interface may be linked to a single class (or a small number of classes) * with the same defining loader as the hidden class or interface. * In such cases, where the hidden class or interface must be coterminous * with a normal class or interface, the {@link ClassOption#STRONG STRONG} * option may be passed in `options`. * This arranges for a hidden class to have the same strong relationship * with the class loader marked as its defining loader, * as a normal class or interface has with its own defining loader. * * If `STRONG` is not used, then the invoker of `defineHiddenClass` * may still prevent a hidden class or interface from being * unloaded by ensuring that the `Class` object is reachable. * * The unloading characteristics are set for each hidden class when it is * defined, and cannot be changed later. An advantage of allowing hidden classes * to be unloaded independently of the class loader marked as their defining loader * is that a very large number of hidden classes may be created by an application. * In contrast, if `STRONG` is used, then the JVM may run out of memory, * just as if normal classes were created by class loaders. * * Classes and interfaces in a nest are allowed to have mutual access to * their private members. The nest relationship is determined by * the `NestHost` attribute (JVMS {@jvms 4.7.28}) and * the `NestMembers` attribute (JVMS {@jvms 4.7.29}) in a `class` file. * By default, a hidden class belongs to a nest consisting only of itself * because a hidden class has no binary name. * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in `options` * to create a hidden class or interface `C` as a member of a nest. * The nest to which `C` belongs is not based on any `NestHost` attribute * in the `ClassFile` structure from which `C` was derived. * Instead, the following rules determine the nest host of `C`: * * If the nest host of the lookup class of this `Lookup` has previously * been determined, then let `H` be the nest host of the lookup class. * Otherwise, the nest host of the lookup class is determined using the * algorithm in JVMS {@jvms 5.4.4}, yielding `H`. * The nest host of `C` is determined to be `H`, * the nest host of the lookup class. * * * A hidden class or interface may be serializable, but this requires a custom * serialization mechanism in order to ensure that instances are properly serialized * and deserialized. The default serialization mechanism supports only classes and * interfaces that are discoverable by their class name. * * @param bytes the bytes that make up the class data, * in the format of a valid `class` file as defined by * The Java Virtual Machine Specification. * @param initialize if `true` the class will be initialized. * @param options {@linkplain ClassOption class options} * @return the `Lookup` object on the hidden class, * with {@linkplain #ORIGINAL original} and * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access * * @throws IllegalAccessException if this `Lookup` does not have * {@linkplain #hasFullPrivilegeAccess() full privilege} access * @throws SecurityException if a security manager is present and it * refuses access * @throws ClassFormatError if `bytes` is not a `ClassFile` structure * @throws UnsupportedClassVersionError if `bytes` is not of a supported major or minor version * @throws IllegalArgumentException if `bytes` denotes a class in a different package * than the lookup class or `bytes` is not a class or interface * (`ACC_MODULE` flag is set in the value of the `access_flags` item) * @throws IncompatibleClassChangeError if the class or interface named as * the direct superclass of `C` is in fact an interface, or if any of the classes * or interfaces named as direct superinterfaces of `C` are not in fact interfaces * @throws ClassCircularityError if any of the superclasses or superinterfaces of * `C` is `C` itself * @throws VerifyError if the newly created class cannot be verified * @throws LinkageError if the newly created class cannot be linked for any other reason * @throws NullPointerException if any parameter is `null` * * @since 15 * @see Class#isHidden() * @jvms 4.2.1 Binary Class and Interface Names * @jvms 4.2.2 Unqualified Names * @jvms 4.7.28 The `NestHost` Attribute * @jvms 4.7.29 The `NestMembers` Attribute * @jvms 5.4.3.1 Class and Interface Resolution * @jvms 5.4.4 Access Control * @jvms 5.3.5 Deriving a `Class` from a `class` File Representation * @jvms 5.4 Linking * @jvms 5.5 Initialization * @jls 12.7 Unloading of Classes and Interfaces */ defineHiddenClass(bytes: number[], initialize: boolean, ...options: ClassOption[]): Lookup; /** * Creates a hidden class or interface from `bytes` with associated * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, * returning a `Lookup` on the newly created class or interface. * * This method is equivalent to calling * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} * as if the hidden class is injected with a private static final unnamed * field which is initialized with the given `classData` at * the first instruction of the class initializer. * The newly created class is linked by the Java Virtual Machine. * * The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} * methods can be used to retrieve the `classData`. * * @apiNote * A framework can create a hidden class with class data with one or more * objects and load the class data as dynamically-computed constant(s) * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) * Class data} is accessible only to the lookup object created by the newly * defined hidden class but inaccessible to other members in the same nest * (unlike private static fields that are accessible to nestmates). * Care should be taken w.r.t. mutability for example when passing * an array or other mutable structure through the class data. * Changing any value stored in the class data at runtime may lead to * unpredictable behavior. * If the class data is a `List`, it is good practice to make it * unmodifiable for example via {@link List#of List::of}. * * @param bytes the class bytes * @param classData pre-initialized class data * @param initialize if `true` the class will be initialized. * @param options {@linkplain ClassOption class options} * @return the `Lookup` object on the hidden class, * with {@linkplain #ORIGINAL original} and * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access * * @throws IllegalAccessException if this `Lookup` does not have * {@linkplain #hasFullPrivilegeAccess() full privilege} access * @throws SecurityException if a security manager is present and it * refuses access * @throws ClassFormatError if `bytes` is not a `ClassFile` structure * @throws UnsupportedClassVersionError if `bytes` is not of a supported major or minor version * @throws IllegalArgumentException if `bytes` denotes a class in a different package * than the lookup class or `bytes` is not a class or interface * (`ACC_MODULE` flag is set in the value of the `access_flags` item) * @throws IncompatibleClassChangeError if the class or interface named as * the direct superclass of `C` is in fact an interface, or if any of the classes * or interfaces named as direct superinterfaces of `C` are not in fact interfaces * @throws ClassCircularityError if any of the superclasses or superinterfaces of * `C` is `C` itself * @throws VerifyError if the newly created class cannot be verified * @throws LinkageError if the newly created class cannot be linked for any other reason * @throws NullPointerException if any parameter is `null` * * @since 16 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) * @see Class#isHidden() * @see MethodHandles#classData(Lookup, String, Class) * @see MethodHandles#classDataAt(Lookup, String, Class, int) * @jvms 4.2.1 Binary Class and Interface Names * @jvms 4.2.2 Unqualified Names * @jvms 4.7.28 The `NestHost` Attribute * @jvms 4.7.29 The `NestMembers` Attribute * @jvms 5.4.3.1 Class and Interface Resolution * @jvms 5.4.4 Access Control * @jvms 5.3.5 Deriving a `Class` from a `class` File Representation * @jvms 5.4 Linking * @jvms 5.5 Initialization * @jls 12.7 Unloading of Classes and Interface */ defineHiddenClassWithClassData(bytes: number[], classData: any, initialize: boolean, ...options: ClassOption[]): Lookup; /** * Displays the name of the class from which lookups are to be made, * followed by "/" and the name of the {@linkplain #previousLookupClass() * previous lookup class} if present. * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) * If there are restrictions on the access permitted to this lookup, * this is indicated by adding a suffix to the class name, consisting * of a slash and a keyword. The keyword represents the strongest * allowed access, and is chosen as follows: * * If no access is allowed, the suffix is "/noaccess". * If only unconditional access is allowed, the suffix is "/publicLookup". * If only public access to types in exported packages is allowed, the suffix is "/public". * If only public and module access are allowed, the suffix is "/module". * If public and package access are allowed, the suffix is "/package". * If public, package, and private access are allowed, the suffix is "/private". * * If none of the above cases apply, it is the case that * {@linkplain #hasFullPrivilegeAccess() full privilege access} * (public, module, package, private, and protected) is allowed. * In this case, no suffix is added. * This is true only of an object obtained originally from * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} * always have restricted access, and will display a suffix. * * (It may seem strange that protected access should be * stronger than private access. Viewed independently from * package access, protected access is the first to be lost, * because it requires a direct subclass relationship between * caller and callee.) * @see #in * * @revised 9 */ toString(): string; /** * Produces a method handle for a static method. * The type of the method handle will be that of the method. * (Since static methods do not take receivers, there is no * additional receiver argument inserted into the method handle type, * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) * The method and all its argument types must be accessible to the lookup object. * * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit (`0x0080`) is set. * * If the returned method handle is invoked, the method's class will * be initialized, if it has not already been initialized. * Example: * {@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, "asList", methodType(List.class, Object[].class)); assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); * } * @param refc the class from which the method is accessed * @param name the name of the method * @param type the type of the method * @return the desired method handle * @throws NoSuchMethodException if the method does not exist * @throws IllegalAccessException if access checking fails, * or if the method is not `static`, * or if the method's variable arity modifier bit * is set and `asVarargsCollector` fails * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null */ findStatic(refc: Class, name: string, type: MethodType): MethodHandle; /** * Produces a method handle for a virtual method. * The type of the method handle will be that of the method, * with the receiver type (usually `refc`) prepended. * The method and all its argument types must be accessible to the lookup object. * * When called, the handle will treat the first argument as a receiver * and, for non-private methods, dispatch on the receiver's type to determine which method * implementation to enter. * For private methods the named method in `refc` will be invoked on the receiver. * (The dispatching action is identical with that performed by an * `invokevirtual` or `invokeinterface` instruction.) * * The first argument will be of type `refc` if the lookup * class has full privileges to access the member. Otherwise * the member must be `protected` and the first argument * will be restricted in type to the lookup class. * * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit (`0x0080`) is set. * * Because of the general equivalence between `invokevirtual` * instructions and method handles produced by `findVirtual`, * if the class is `MethodHandle` and the name string is * `invokeExact` or `invoke`, the resulting * method handle is equivalent to one produced by * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} * with the same `type` argument. * * If the class is `VarHandle` and the name string corresponds to * the name of a signature-polymorphic access mode method, the resulting * method handle is equivalent to one produced by * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with * the access mode corresponding to the name string and with the same * `type` arguments. * * Example: * {@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle MH_concat = publicLookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, "hashCode", methodType(int.class)); MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, "hashCode", methodType(int.class)); assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); // interface method: MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, "subSequence", methodType(CharSequence.class, int.class, int.class)); assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); // constructor "internal method" must be accessed differently: MethodType MT_newString = methodType(void.class); //()V for new String() try { assertEquals("impossible", lookup() .findVirtual(String.class, "", MT_newString)); } catch (NoSuchMethodException ex) { } // OK MethodHandle MH_newString = publicLookup() .findConstructor(String.class, MT_newString); assertEquals("", (String) MH_newString.invokeExact()); * } * * @param refc the class or interface from which the method is accessed * @param name the name of the method * @param type the type of the method, with the receiver argument omitted * @return the desired method handle * @throws NoSuchMethodException if the method does not exist * @throws IllegalAccessException if access checking fails, * or if the method is `static`, * or if the method's variable arity modifier bit * is set and `asVarargsCollector` fails * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null */ findVirtual(refc: Class, name: string, type: MethodType): MethodHandle; /** * Produces a method handle which creates an object and initializes it, using * the constructor of the specified type. * The parameter types of the method handle will be those of the constructor, * while the return type will be a reference to the constructor's class. * The constructor and all its argument types must be accessible to the lookup object. * * The requested type must have a return type of `void`. * (This is consistent with the JVM's treatment of constructor type descriptors.) * * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the constructor's variable arity modifier bit (`0x0080`) is set. * * If the returned method handle is invoked, the constructor's class will * be initialized, if it has not already been initialized. * Example: * {@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle MH_newArrayList = publicLookup().findConstructor( ArrayList.class, methodType(void.class, Collection.class)); Collection orig = Arrays.asList("x", "y"); Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); assert(orig != copy); assertEquals(orig, copy); // a variable-arity constructor: MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( ProcessBuilder.class, methodType(void.class, String[].class)); ProcessBuilder pb = (ProcessBuilder) MH_newProcessBuilder.invoke("x", "y", "z"); assertEquals("[x, y, z]", pb.command().toString()); * } * @param refc the class or interface from which the method is accessed * @param type the type of the method, with the receiver argument omitted, and a void return type * @return the desired method handle * @throws NoSuchMethodException if the constructor does not exist * @throws IllegalAccessException if access checking fails * or if the method's variable arity modifier bit * is set and `asVarargsCollector` fails * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null */ findConstructor(refc: Class, type: MethodType): MethodHandle; /** * Looks up a class by name from the lookup context defined by this `Lookup` object, * as if resolved by an `ldc` instruction. * Such a resolution, as specified in JVMS 5.4.3.1 section, attempts to locate and load the class, * and then determines whether the class is accessible to this lookup object. * * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, * its class loader, and the {@linkplain #lookupModes() lookup modes}. * * @param targetName the fully qualified name of the class to be looked up. * @return the requested class. * @throws SecurityException if a security manager is present and it * refuses access * @throws LinkageError if the linkage fails * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. * @throws IllegalAccessException if the class is not accessible, using the allowed access * modes. * @since 9 * @jvms 5.4.3.1 Class and Interface Resolution */ findClass(targetName: string): Class; /** * Ensures that `targetClass` has been initialized. The class * to be initialized must be {@linkplain #accessClass accessible} * to this `Lookup` object. This method causes `targetClass` * to be initialized if it has not been already initialized, * as specified in JVMS {@jvms 5.5}. * * @param targetClass the class to be initialized * @return `targetClass` that has been initialized * * @throws IllegalArgumentException if `targetClass` is a primitive type or `void` * or array class * @throws IllegalAccessException if `targetClass` is not * {@linkplain #accessClass accessible} to this lookup * @throws ExceptionInInitializerError if the class initialization provoked * by this method fails * @throws SecurityException if a security manager is present and it * refuses access * @since 15 * @jvms 5.5 Initialization */ ensureInitialized(targetClass: Class): Class; /** * Determines if a class can be accessed from the lookup context defined by * this `Lookup` object. The static initializer of the class is not run. * * If the `targetClass` is in the same module as the lookup class, * the lookup class is `LC` in module `M1` and * the previous lookup class is in module `M0` or * `null` if not present, * `targetClass` is accessible if and only if one of the following is true: * * If this lookup has {@link #PRIVATE} access, `targetClass` is * `LC` or other class in the same nest of `LC`. * If this lookup has {@link #PACKAGE} access, `targetClass` is * in the same runtime package of `LC`. * If this lookup has {@link #MODULE} access, `targetClass` is * a public type in `M1`. * If this lookup has {@link #PUBLIC} access, `targetClass` is * a public type in a package exported by `M1` to at least `M0` * if the previous lookup class is present; otherwise, `targetClass` * is a public type in a package exported by `M1` unconditionally. * * * * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup * can access public types in all modules when the type is in a package * that is exported unconditionally. * * Otherwise, the target class is in a different module from `lookupClass`, * and if this lookup does not have `PUBLIC` access, `lookupClass` * is inaccessible. * * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, * `M1` is the module containing `lookupClass` and * `M2` is the module containing `targetClass`, * then `targetClass` is accessible if and only if * * `M1` reads `M2`, and * `targetClass` is public and in a package exported by * `M2` at least to `M1`. * * * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, * `M1` and `M2` are as before, and `M0` is the module * containing the previous lookup class, then `targetClass` is accessible * if and only if one of the following is true: * * `targetClass` is in `M0` and `M1` * {@linkplain Module#reads reads} `M0` and the type is * in a package that is exported to at least `M1`. * `targetClass` is in `M1` and `M0` * {@linkplain Module#reads reads} `M1` and the type is * in a package that is exported to at least `M0`. * `targetClass` is in a third module `M2` and both `M0` * and `M1` reads `M2` and the type is in a package * that is exported to at least both `M0` and `M2`. * * * Otherwise, `targetClass` is not accessible. * * @param targetClass the class to be access-checked * @return the class that has been access-checked * @throws IllegalAccessException if the class is not accessible from the lookup class * and previous lookup class, if present, using the allowed access modes. * @throws SecurityException if a security manager is present and it * refuses access * @since 9 * @see Cross-module lookups */ accessClass(targetClass: Class): Class; /** * Produces an early-bound method handle for a virtual method. * It will bypass checks for overriding methods on the receiver, * as if called from an `invokespecial` * instruction from within the explicitly specified `specialCaller`. * The type of the method handle will be that of the method, * with a suitably restricted receiver type prepended. * (The receiver type will be `specialCaller` or a subtype.) * The method and all its argument types must be accessible * to the lookup object. * * Before method resolution, * if the explicitly specified caller class is not identical with the * lookup class, or if this lookup object does not have * private access * privileges, the access fails. * * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit (`0x0080`) is set. * * (Note: JVM internal methods named `""` are not visible to this API, * even though the `invokespecial` instruction can refer to them * in special circumstances. Use {@link #findConstructor findConstructor} * to access instance initialization methods in a safe manner.) * Example: * {@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... static class Listie extends ArrayList { public String toString() { return "[wee Listie]"; } static Lookup lookup() { return MethodHandles.lookup(); } } ... // no access to constructor via invokeSpecial: MethodHandle MH_newListie = Listie.lookup() .findConstructor(Listie.class, methodType(void.class)); Listie l = (Listie) MH_newListie.invokeExact(); try { assertEquals("impossible", Listie.lookup().findSpecial( Listie.class, "", methodType(void.class), Listie.class)); } catch (NoSuchMethodException ex) { } // OK // access to super and self methods via invokeSpecial: MethodHandle MH_super = Listie.lookup().findSpecial( ArrayList.class, "toString" , methodType(String.class), Listie.class); MethodHandle MH_this = Listie.lookup().findSpecial( Listie.class, "toString" , methodType(String.class), Listie.class); MethodHandle MH_duper = Listie.lookup().findSpecial( Object.class, "toString" , methodType(String.class), Listie.class); assertEquals("[]", (String) MH_super.invokeExact(l)); assertEquals(""+l, (String) MH_this.invokeExact(l)); assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method try { assertEquals("inaccessible", Listie.lookup().findSpecial( String.class, "toString", methodType(String.class), Listie.class)); } catch (IllegalAccessException ex) { } // OK Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method * } * * @param refc the class or interface from which the method is accessed * @param name the name of the method (which must not be "") * @param type the type of the method, with the receiver argument omitted * @param specialCaller the proposed calling class to perform the `invokespecial` * @return the desired method handle * @throws NoSuchMethodException if the method does not exist * @throws IllegalAccessException if access checking fails, * or if the method is `static`, * or if the method's variable arity modifier bit * is set and `asVarargsCollector` fails * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null */ findSpecial(refc: Class, name: string, type: MethodType, specialCaller: Class): MethodHandle; /** * Produces a method handle giving read access to a non-static field. * The type of the method handle will have a return type of the field's * value type. * The method handle's single argument will be the instance containing * the field. * Access checking is performed immediately on behalf of the lookup class. * @param refc the class or interface from which the method is accessed * @param name the field's name * @param type the field's type * @return a method handle which can load values from the field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is `static` * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null * @see #findVarHandle(Class, String, Class) */ findGetter(refc: Class, name: string, type: Class): MethodHandle; /** * Produces a method handle giving write access to a non-static field. * The type of the method handle will have a void return type. * The method handle will take two arguments, the instance containing * the field, and the value to be stored. * The second argument will be of the field's value type. * Access checking is performed immediately on behalf of the lookup class. * @param refc the class or interface from which the method is accessed * @param name the field's name * @param type the field's type * @return a method handle which can store values into the field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is `static` * or `final` * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null * @see #findVarHandle(Class, String, Class) */ findSetter(refc: Class, name: string, type: Class): MethodHandle; /** * Produces a VarHandle giving access to a non-static field `name` * of type `type` declared in a class of type `recv`. * The VarHandle's variable type is `type` and it has one * coordinate type, `recv`. * * Access checking is performed immediately on behalf of the lookup * class. * * Certain access modes of the returned VarHandle are unsupported under * the following conditions: * * if the field is declared `final`, then the write, atomic * update, numeric atomic update, and bitwise atomic update access * modes are unsupported. * if the field type is anything other than `byte`, * `short`, `char`, `int`, `long`, * `float`, or `double` then numeric atomic update * access modes are unsupported. * if the field type is anything other than `boolean`, * `byte`, `short`, `char`, `int` or * `long` then bitwise atomic update access modes are * unsupported. * * * If the field is declared `volatile` then the returned VarHandle * will override access to the field (effectively ignore the * `volatile` declaration) in accordance to its specified * access modes. * * If the field type is `float` or `double` then numeric * and atomic update access modes compare values using their bitwise * representation (see {@link Float#floatToRawIntBits} and * {@link Double#doubleToRawLongBits}, respectively). * @apiNote * Bitwise comparison of `float` values or `double` values, * as performed by the numeric and atomic update access modes, differ * from the primitive `==` operator and the {@link Float#equals} * and {@link Double#equals} methods, specifically with respect to * comparing NaN values or comparing `-0.0` with `+0.0`. * Care should be taken when performing a compare and set or a compare * and exchange operation with such values since the operation may * unexpectedly fail. * There are many possible NaN values that are considered to be * `NaN` in Java, although no IEEE 754 floating-point operation * provided by Java can distinguish between them. Operation failure can * occur if the expected or witness value is a NaN value and it is * transformed (perhaps in a platform specific manner) into another NaN * value, and thus has a different bitwise representation (see * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more * details). * The values `-0.0` and `+0.0` have different bitwise * representations but are considered equal when using the primitive * `==` operator. Operation failure can occur if, for example, a * numeric algorithm computes an expected value to be say `-0.0` * and previously computed the witness value to be say `+0.0`. * @param recv the receiver class, of type `R`, that declares the * non-static field * @param name the field's name * @param type the field's type, of type `T` * @return a VarHandle giving access to non-static fields. * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is `static` * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null * @since 9 */ findVarHandle(recv: Class, name: string, type: Class): VarHandle; /** * Produces a method handle giving read access to a static field. * The type of the method handle will have a return type of the field's * value type. * The method handle will take no arguments. * Access checking is performed immediately on behalf of the lookup class. * * If the returned method handle is invoked, the field's class will * be initialized, if it has not already been initialized. * @param refc the class or interface from which the method is accessed * @param name the field's name * @param type the field's type * @return a method handle which can load values from the field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is not `static` * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null */ findStaticGetter(refc: Class, name: string, type: Class): MethodHandle; /** * Produces a method handle giving write access to a static field. * The type of the method handle will have a void return type. * The method handle will take a single * argument, of the field's value type, the value to be stored. * Access checking is performed immediately on behalf of the lookup class. * * If the returned method handle is invoked, the field's class will * be initialized, if it has not already been initialized. * @param refc the class or interface from which the method is accessed * @param name the field's name * @param type the field's type * @return a method handle which can store values into the field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is not `static` * or is `final` * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null */ findStaticSetter(refc: Class, name: string, type: Class): MethodHandle; /** * Produces a VarHandle giving access to a static field `name` of * type `type` declared in a class of type `decl`. * The VarHandle's variable type is `type` and it has no * coordinate types. * * Access checking is performed immediately on behalf of the lookup * class. * * If the returned VarHandle is operated on, the declaring class will be * initialized, if it has not already been initialized. * * Certain access modes of the returned VarHandle are unsupported under * the following conditions: * * if the field is declared `final`, then the write, atomic * update, numeric atomic update, and bitwise atomic update access * modes are unsupported. * if the field type is anything other than `byte`, * `short`, `char`, `int`, `long`, * `float`, or `double`, then numeric atomic update * access modes are unsupported. * if the field type is anything other than `boolean`, * `byte`, `short`, `char`, `int` or * `long` then bitwise atomic update access modes are * unsupported. * * * If the field is declared `volatile` then the returned VarHandle * will override access to the field (effectively ignore the * `volatile` declaration) in accordance to its specified * access modes. * * If the field type is `float` or `double` then numeric * and atomic update access modes compare values using their bitwise * representation (see {@link Float#floatToRawIntBits} and * {@link Double#doubleToRawLongBits}, respectively). * @apiNote * Bitwise comparison of `float` values or `double` values, * as performed by the numeric and atomic update access modes, differ * from the primitive `==` operator and the {@link Float#equals} * and {@link Double#equals} methods, specifically with respect to * comparing NaN values or comparing `-0.0` with `+0.0`. * Care should be taken when performing a compare and set or a compare * and exchange operation with such values since the operation may * unexpectedly fail. * There are many possible NaN values that are considered to be * `NaN` in Java, although no IEEE 754 floating-point operation * provided by Java can distinguish between them. Operation failure can * occur if the expected or witness value is a NaN value and it is * transformed (perhaps in a platform specific manner) into another NaN * value, and thus has a different bitwise representation (see * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more * details). * The values `-0.0` and `+0.0` have different bitwise * representations but are considered equal when using the primitive * `==` operator. Operation failure can occur if, for example, a * numeric algorithm computes an expected value to be say `-0.0` * and previously computed the witness value to be say `+0.0`. * @param decl the class that declares the static field * @param name the field's name * @param type the field's type, of type `T` * @return a VarHandle giving access to a static field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is not `static` * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null * @since 9 */ findStaticVarHandle(decl: Class, name: string, type: Class): VarHandle; /** * Produces an early-bound method handle for a non-static method. * The receiver must have a supertype `defc` in which a method * of the given name and type is accessible to the lookup class. * The method and all its argument types must be accessible to the lookup object. * The type of the method handle will be that of the method, * without any insertion of an additional receiver parameter. * The given receiver will be bound into the method handle, * so that every call to the method handle will invoke the * requested method on the given receiver. * * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit (`0x0080`) is set * and the trailing array argument is not the only argument. * (If the trailing array argument is the only argument, * the given receiver value will be bound to it.) * * This is almost equivalent to the following code, with some differences noted below: * {@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle mh0 = lookup().findVirtual(defc, name, type); MethodHandle mh1 = mh0.bindTo(receiver); mh1 = mh1.withVarargs(mh0.isVarargsCollector()); return mh1; * } * where `defc` is either `receiver.getClass()` or a super * type of that class, in which the requested method is accessible * to the lookup class. * (Unlike `bind`, `bindTo` does not preserve variable arity. * Also, `bindTo` may throw a `ClassCastException` in instances where `bind` would * throw an `IllegalAccessException`, as in the case where the member is `protected` and * the receiver is restricted by `findVirtual` to the lookup class.) * @param receiver the object from which the method is accessed * @param name the name of the method * @param type the type of the method, with the receiver argument omitted * @return the desired method handle * @throws NoSuchMethodException if the method does not exist * @throws IllegalAccessException if access checking fails * or if the method's variable arity modifier bit * is set and `asVarargsCollector` fails * @throws SecurityException if a security manager is present and it * refuses access * @throws NullPointerException if any argument is null * @see MethodHandle#bindTo * @see #findVirtual */ bind(receiver: any, name: string, type: MethodType): MethodHandle; /** * Makes a direct method handle * to m, if the lookup class has permission. * If m is non-static, the receiver argument is treated as an initial argument. * If m is virtual, overriding is respected on every call. * Unlike the Core Reflection API, exceptions are not wrapped. * The type of the method handle will be that of the method, * with the receiver type prepended (but only if it is non-static). * If the method's `accessible` flag is not set, * access checking is performed immediately on behalf of the lookup class. * If m is not public, do not share the resulting handle with untrusted parties. * * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit (`0x0080`) is set. * * If m is static, and * if the returned method handle is invoked, the method's class will * be initialized, if it has not already been initialized. * @param m the reflected method * @return a method handle which can invoke the reflected method * @throws IllegalAccessException if access checking fails * or if the method's variable arity modifier bit * is set and `asVarargsCollector` fails * @throws NullPointerException if the argument is null */ unreflect(m: Method): MethodHandle; /** * Produces a method handle for a reflected method. * It will bypass checks for overriding methods on the receiver, * as if called from an `invokespecial` * instruction from within the explicitly specified `specialCaller`. * The type of the method handle will be that of the method, * with a suitably restricted receiver type prepended. * (The receiver type will be `specialCaller` or a subtype.) * If the method's `accessible` flag is not set, * access checking is performed immediately on behalf of the lookup class, * as if `invokespecial` instruction were being linked. * * Before method resolution, * if the explicitly specified caller class is not identical with the * lookup class, or if this lookup object does not have * private access * privileges, the access fails. * * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit (`0x0080`) is set. * @param m the reflected method * @param specialCaller the class nominally calling the method * @return a method handle which can invoke the reflected method * @throws IllegalAccessException if access checking fails, * or if the method is `static`, * or if the method's variable arity modifier bit * is set and `asVarargsCollector` fails * @throws NullPointerException if any argument is null */ unreflectSpecial(m: Method, specialCaller: Class): MethodHandle; /** * Produces a method handle for a reflected constructor. * The type of the method handle will be that of the constructor, * with the return type changed to the declaring class. * The method handle will perform a `newInstance` operation, * creating a new instance of the constructor's class on the * arguments passed to the method handle. * * If the constructor's `accessible` flag is not set, * access checking is performed immediately on behalf of the lookup class. * * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the constructor's variable arity modifier bit (`0x0080`) is set. * * If the returned method handle is invoked, the constructor's class will * be initialized, if it has not already been initialized. * @param c the reflected constructor * @return a method handle which can invoke the reflected constructor * @throws IllegalAccessException if access checking fails * or if the method's variable arity modifier bit * is set and `asVarargsCollector` fails * @throws NullPointerException if the argument is null */ unreflectConstructor(c: Constructor): MethodHandle; /** * Produces a method handle giving read access to a reflected field. * The type of the method handle will have a return type of the field's * value type. * If the field is `static`, the method handle will take no arguments. * Otherwise, its single argument will be the instance containing * the field. * If the `Field` object's `accessible` flag is not set, * access checking is performed immediately on behalf of the lookup class. * * If the field is static, and * if the returned method handle is invoked, the field's class will * be initialized, if it has not already been initialized. * @param f the reflected field * @return a method handle which can load values from the reflected field * @throws IllegalAccessException if access checking fails * @throws NullPointerException if the argument is null */ unreflectGetter(f: Field): MethodHandle; /** * Produces a method handle giving write access to a reflected field. * The type of the method handle will have a void return type. * If the field is `static`, the method handle will take a single * argument, of the field's value type, the value to be stored. * Otherwise, the two arguments will be the instance containing * the field, and the value to be stored. * If the `Field` object's `accessible` flag is not set, * access checking is performed immediately on behalf of the lookup class. * * If the field is `final`, write access will not be * allowed and access checking will fail, except under certain * narrow circumstances documented for {@link Field#set Field.set}. * A method handle is returned only if a corresponding call to * the `Field` object's `set` method could return * normally. In particular, fields which are both `static` * and `final` may never be set. * * If the field is `static`, and * if the returned method handle is invoked, the field's class will * be initialized, if it has not already been initialized. * @param f the reflected field * @return a method handle which can store values into the reflected field * @throws IllegalAccessException if access checking fails, * or if the field is `final` and write access * is not enabled on the `Field` object * @throws NullPointerException if the argument is null */ unreflectSetter(f: Field): MethodHandle; /** * Produces a VarHandle giving access to a reflected field `f` * of type `T` declared in a class of type `R`. * The VarHandle's variable type is `T`. * If the field is non-static the VarHandle has one coordinate type, * `R`. Otherwise, the field is static, and the VarHandle has no * coordinate types. * * Access checking is performed immediately on behalf of the lookup * class, regardless of the value of the field's `accessible` * flag. * * If the field is static, and if the returned VarHandle is operated * on, the field's declaring class will be initialized, if it has not * already been initialized. * * Certain access modes of the returned VarHandle are unsupported under * the following conditions: * * if the field is declared `final`, then the write, atomic * update, numeric atomic update, and bitwise atomic update access * modes are unsupported. * if the field type is anything other than `byte`, * `short`, `char`, `int`, `long`, * `float`, or `double` then numeric atomic update * access modes are unsupported. * if the field type is anything other than `boolean`, * `byte`, `short`, `char`, `int` or * `long` then bitwise atomic update access modes are * unsupported. * * * If the field is declared `volatile` then the returned VarHandle * will override access to the field (effectively ignore the * `volatile` declaration) in accordance to its specified * access modes. * * If the field type is `float` or `double` then numeric * and atomic update access modes compare values using their bitwise * representation (see {@link Float#floatToRawIntBits} and * {@link Double#doubleToRawLongBits}, respectively). * @apiNote * Bitwise comparison of `float` values or `double` values, * as performed by the numeric and atomic update access modes, differ * from the primitive `==` operator and the {@link Float#equals} * and {@link Double#equals} methods, specifically with respect to * comparing NaN values or comparing `-0.0` with `+0.0`. * Care should be taken when performing a compare and set or a compare * and exchange operation with such values since the operation may * unexpectedly fail. * There are many possible NaN values that are considered to be * `NaN` in Java, although no IEEE 754 floating-point operation * provided by Java can distinguish between them. Operation failure can * occur if the expected or witness value is a NaN value and it is * transformed (perhaps in a platform specific manner) into another NaN * value, and thus has a different bitwise representation (see * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more * details). * The values `-0.0` and `+0.0` have different bitwise * representations but are considered equal when using the primitive * `==` operator. Operation failure can occur if, for example, a * numeric algorithm computes an expected value to be say `-0.0` * and previously computed the witness value to be say `+0.0`. * @param f the reflected field, with a field of type `T`, and * a declaring class of type `R` * @return a VarHandle giving access to non-static fields or a static * field * @throws IllegalAccessException if access checking fails * @throws NullPointerException if the argument is null * @since 9 */ unreflectVarHandle(f: Field): VarHandle; /** * Cracks a direct method handle * created by this lookup object or a similar one. * Security and access checks are performed to ensure that this lookup object * is capable of reproducing the target method handle. * This means that the cracking may fail if target is a direct method handle * but was created by an unrelated lookup object. * This can happen if the method handle is caller sensitive * and was created by a lookup object for a different class. * @param target a direct method handle to crack into symbolic reference components * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object * @throws SecurityException if a security manager is present and it * refuses access * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails * @throws NullPointerException if the target is `null` * @see MethodHandleInfo * @since 1.8 */ revealDirect(target: MethodHandle): MethodHandleInfo; /** * Returns `true` if this lookup has `PRIVATE` and `MODULE` access. * @return `true` if this lookup has `PRIVATE` and `MODULE` access. * * @deprecated This method was originally designed to test `PRIVATE` access * that implies full privilege access but `MODULE` access has since become * independent of `PRIVATE` access. It is recommended to call * {@link #hasFullPrivilegeAccess()} instead. * @since 9 */ hasPrivateAccess(): boolean; /** * Returns `true` if this lookup has full privilege access, * i.e. `PRIVATE` and `MODULE` access. * A `Lookup` object must have full privilege access in order to * access all members that are allowed to the * {@linkplain #lookupClass() lookup class}. * * @return `true` if this lookup has full privilege access. * @since 14 * @see private and module access */ hasFullPrivilegeAccess(): boolean; } } declare module 'java.lang.module.ModuleDescriptor.Exports' { import { Enum } from 'java.lang'; /** * A modifier on an exported package. * * @see Exports#modifiers() * @since 9 */ export class Modifier extends Enum { /** * The export was not explicitly or implicitly declared in the * source of the module declaration. */ static readonly SYNTHETIC: Modifier; /** * The export was implicitly declared in the source of the module * declaration. */ static readonly MANDATED: Modifier; static valueOf(name: string): Modifier; static values(): Modifier[]; } } declare module 'java.lang' { import { Constable, ClassDesc } from 'java.lang.constant'; import { Enumeration, Set, Optional, EnumSet, ArrayList, Iterator, ResourceBundle, List, Properties, Map, Spliterator } from 'java.util'; import { Logger } from 'java.lang.System'; import { Stream, IntStream } from 'java.util.stream'; import { Annotation } from 'java.lang.annotation'; import { Controller } from 'java.lang.ModuleLayer'; import { ExtendedOption, Option } from 'java.lang.StackWalker'; import { CharBuffer } from 'java.nio'; import { Channel } from 'java.nio.channels'; import { Certificate } from 'java.security.cert'; import { SoftReference } from 'java.lang.ref'; import { InetAddress, URL } from 'java.net'; import { EnumDesc } from 'java.lang.Enum'; import { Info } from 'java.lang.ProcessHandle'; import { State, UncaughtExceptionHandler } from 'java.lang.Thread'; import { Redirect } from 'java.lang.ProcessBuilder'; import { OfField } from 'java.lang.invoke.TypeDescriptor'; import { Field, AnnotatedType, Type, TypeVariable, Constructor, AnnotatedElement, Method, GenericDeclaration, RecordComponent } from 'java.lang.reflect'; import { ProtectionDomain, BasicPermission, AccessControlContext, Permission } from 'java.security'; import { ThreadLocalMap } from 'java.lang.ThreadLocal'; import { VersionInfo } from 'java.lang.Package'; import { CompletableFuture, TimeUnit, ConcurrentHashMap } from 'java.util.concurrent'; import { Version } from 'java.lang.Runtime'; import { AtomicInteger } from 'java.util.concurrent.atomic'; import { ModuleDescriptor, Configuration } from 'java.lang.module'; import { PrintStream, Serializable, ObjectStreamField, InputStream, OutputStream, Console, File, FileDescriptor, PrintWriter } from 'java.io'; import { Entry, Version as java_lang_ClassValue_Version, Identity, ClassValueMap } from 'java.lang.ClassValue'; import { AnnotationData, ReflectionData } from 'java.lang.Class'; import { Function, Consumer, Supplier } from 'java.util.function'; /** * Indicates that a method declaration is intended to override a * method declaration in a supertype. If a method is annotated with * this annotation type compilers are required to generate an error * message unless at least one of the following conditions hold: * * * The method does override or implement a method declared in a * supertype. * * The method has a signature that is override-equivalent to that of * any public method declared in {@linkplain Object}. * * * @author Peter von der Ahé * @author Joshua Bloch * @jls 8.4.8 Inheritance, Overriding, and Hiding * @jls 9.4.1 Inheritance and Overriding * @jls 9.6.4.4 @Override * @since 1.5 */ export class Override { } /** * A thread is a thread of execution in a program. The Java * Virtual Machine allows an application to have multiple threads of * execution running concurrently. * * Every thread has a priority. Threads with higher priority are * executed in preference to threads with lower priority. Each thread * may or may not also be marked as a daemon. When code running in * some thread creates a new `Thread` object, the new * thread has its priority initially set equal to the priority of the * creating thread, and is a daemon thread if and only if the * creating thread is a daemon. * * When a Java Virtual Machine starts up, there is usually a single * non-daemon thread (which typically calls the method named * `main` of some designated class). The Java Virtual * Machine continues to execute threads until either of the following * occurs: * * The `exit` method of class `Runtime` has been * called and the security manager has permitted the exit operation * to take place. * All threads that are not daemon threads have died, either by * returning from the call to the `run` method or by * throwing an exception that propagates beyond the `run` * method. * * * There are two ways to create a new thread of execution. One is to * declare a class to be a subclass of `Thread`. This * subclass should override the `run` method of class * `Thread`. An instance of the subclass can then be * allocated and started. For example, a thread that computes primes * larger than a stated value could be written as follows: * * class PrimeThread extends Thread { * long minPrime; * PrimeThread(long minPrime) { * this.minPrime = minPrime; * } * * public void run() { * // compute primes larger than minPrime *  . . . * } * } * * * The following code would then create a thread and start it running: * * PrimeThread p = new PrimeThread(143); * p.start(); * * * The other way to create a thread is to declare a class that * implements the `Runnable` interface. That class then * implements the `run` method. An instance of the class can * then be allocated, passed as an argument when creating * `Thread`, and started. The same example in this other * style looks like the following: * * class PrimeRun implements Runnable { * long minPrime; * PrimeRun(long minPrime) { * this.minPrime = minPrime; * } * * public void run() { * // compute primes larger than minPrime *  . . . * } * } * * * The following code would then create a thread and start it running: * * PrimeRun p = new PrimeRun(143); * new Thread(p).start(); * * * Every thread has a name for identification purposes. More than * one thread may have the same name. If a name is not specified when * a thread is created, a new name is generated for it. * * Unless otherwise noted, passing a `null` argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * * @see Runnable * @see Runtime#exit(int) * @see #run() * @see #stop() * @since 1.0 */ export class Thread extends Runnable { /** * The minimum priority that a thread can have. */ static readonly MIN_PRIORITY: number; /** * The default priority that is assigned to a thread. */ static readonly NORM_PRIORITY: number; /** * The maximum priority that a thread can have. */ static readonly MAX_PRIORITY: number; /** * Returns a reference to the currently executing thread object. * * @return the currently executing thread. */ static currentThread(): Thread; /** * A hint to the scheduler that the current thread is willing to yield * its current use of a processor. The scheduler is free to ignore this * hint. * * Yield is a heuristic attempt to improve relative progression * between threads that would otherwise over-utilise a CPU. Its use * should be combined with detailed profiling and benchmarking to * ensure that it actually has the desired effect. * * It is rarely appropriate to use this method. It may be useful * for debugging or testing purposes, where it may help to reproduce * bugs due to race conditions. It may also be useful when designing * concurrency control constructs such as the ones in the * {@link java.util.concurrent.locks} package. */ static yield(): void; /** * Causes the currently executing thread to sleep (temporarily cease * execution) for the specified number of milliseconds, subject to * the precision and accuracy of system timers and schedulers. The thread * does not lose ownership of any monitors. * * @param millis * the length of time to sleep in milliseconds * * @throws IllegalArgumentException * if the value of `millis` is negative * * @throws InterruptedException * if any thread has interrupted the current thread. The * interrupted status of the current thread is * cleared when this exception is thrown. */ static sleep(millis: number): void; /** * Causes the currently executing thread to sleep (temporarily cease * execution) for the specified number of milliseconds plus the specified * number of nanoseconds, subject to the precision and accuracy of system * timers and schedulers. The thread does not lose ownership of any * monitors. * * @param millis * the length of time to sleep in milliseconds * * @param nanos * `0-999999` additional nanoseconds to sleep * * @throws IllegalArgumentException * if the value of `millis` is negative, or the value of * `nanos` is not in the range `0-999999` * * @throws InterruptedException * if any thread has interrupted the current thread. The * interrupted status of the current thread is * cleared when this exception is thrown. */ static sleep(millis: number, nanos: number): void; /** * Indicates that the caller is momentarily unable to progress, until the * occurrence of one or more actions on the part of other activities. By * invoking this method within each iteration of a spin-wait loop construct, * the calling thread indicates to the runtime that it is busy-waiting. * The runtime may take action to improve the performance of invoking * spin-wait loop constructions. * * @apiNote * As an example consider a method in a class that spins in a loop until * some flag is set outside of that method. A call to the `onSpinWait` * method should be placed inside the spin loop. * {@code * class EventHandler { * volatile boolean eventNotificationNotReceived; * void waitForEventAndHandleIt() { * while ( eventNotificationNotReceived ) { * java.lang.Thread.onSpinWait(); * } * readAndProcessEvent(); * } * * void readAndProcessEvent() { * // Read event from some source and process it * . . . * } * } * } * * The code above would remain correct even if the `onSpinWait` * method was not called at all. However on some architectures the Java * Virtual Machine may issue the processor instructions to address such * code patterns in a more beneficial way. * * @since 9 */ static onSpinWait(): void; /** * Allocates a new `Thread` object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * `(null, null, gname)`, where `gname` is a newly generated * name. Automatically generated names are of the form * `"Thread-"+`n, where n is an integer. */ constructor(); /** * Allocates a new `Thread` object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * `(null, target, gname)`, where `gname` is a newly generated * name. Automatically generated names are of the form * `"Thread-"+`n, where n is an integer. * * @param target * the object whose `run` method is invoked when this thread * is started. If `null`, this classes `run` method does * nothing. */ constructor(target: Runnable); /** * Allocates a new `Thread` object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * `(group, target, gname)` ,where `gname` is a newly generated * name. Automatically generated names are of the form * `"Thread-"+`n, where n is an integer. * * @param group * the thread group. If `null` and there is a security * manager, the group is determined by {@linkplain * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. * If there is not a security manager or ` * SecurityManager.getThreadGroup()` returns `null`, the group * is set to the current thread's thread group. * * @param target * the object whose `run` method is invoked when this thread * is started. If `null`, this thread's run method is invoked. * * @throws SecurityException * if the current thread cannot create a thread in the specified * thread group */ constructor(group: ThreadGroup, target: Runnable); /** * Allocates a new `Thread` object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * `(null, null, name)`. * * @param name * the name of the new thread */ constructor(name: string); /** * Allocates a new `Thread` object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * `(group, null, name)`. * * @param group * the thread group. If `null` and there is a security * manager, the group is determined by {@linkplain * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. * If there is not a security manager or ` * SecurityManager.getThreadGroup()` returns `null`, the group * is set to the current thread's thread group. * * @param name * the name of the new thread * * @throws SecurityException * if the current thread cannot create a thread in the specified * thread group */ constructor(group: ThreadGroup, name: string); /** * Allocates a new `Thread` object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * `(null, target, name)`. * * @param target * the object whose `run` method is invoked when this thread * is started. If `null`, this thread's run method is invoked. * * @param name * the name of the new thread */ constructor(target: Runnable, name: string); /** * Allocates a new `Thread` object so that it has `target` * as its run object, has the specified `name` as its name, * and belongs to the thread group referred to by `group`. * * If there is a security manager, its * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess} * method is invoked with the ThreadGroup as its argument. * * In addition, its `checkPermission` method is invoked with * the `RuntimePermission("enableContextClassLoaderOverride")` * permission when invoked directly or indirectly by the constructor * of a subclass which overrides the `getContextClassLoader` * or `setContextClassLoader` methods. * * The priority of the newly created thread is set equal to the * priority of the thread creating it, that is, the currently running * thread. The method {@linkplain #setPriority setPriority} may be * used to change the priority to a new value. * * The newly created thread is initially marked as being a daemon * thread if and only if the thread creating it is currently marked * as a daemon thread. The method {@linkplain #setDaemon setDaemon} * may be used to change whether or not a thread is a daemon. * * @param group * the thread group. If `null` and there is a security * manager, the group is determined by {@linkplain * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. * If there is not a security manager or ` * SecurityManager.getThreadGroup()` returns `null`, the group * is set to the current thread's thread group. * * @param target * the object whose `run` method is invoked when this thread * is started. If `null`, this thread's run method is invoked. * * @param name * the name of the new thread * * @throws SecurityException * if the current thread cannot create a thread in the specified * thread group or cannot override the context class loader methods. */ constructor(group: ThreadGroup, target: Runnable, name: string); /** * Allocates a new `Thread` object so that it has `target` * as its run object, has the specified `name` as its name, * and belongs to the thread group referred to by `group`, and has * the specified stack size. * * This constructor is identical to {@link * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact * that it allows the thread stack size to be specified. The stack size * is the approximate number of bytes of address space that the virtual * machine is to allocate for this thread's stack. The effect of the * `stackSize` parameter, if any, is highly platform dependent. * * On some platforms, specifying a higher value for the * `stackSize` parameter may allow a thread to achieve greater * recursion depth before throwing a {@link StackOverflowError}. * Similarly, specifying a lower value may allow a greater number of * threads to exist concurrently without throwing an {@link * OutOfMemoryError} (or other internal error). The details of * the relationship between the value of the `stackSize` parameter * and the maximum recursion depth and concurrency level are * platform-dependent. On some platforms, the value of the * `stackSize` parameter may have no effect whatsoever. * * The virtual machine is free to treat the `stackSize` * parameter as a suggestion. If the specified value is unreasonably low * for the platform, the virtual machine may instead use some * platform-specific minimum value; if the specified value is unreasonably * high, the virtual machine may instead use some platform-specific * maximum. Likewise, the virtual machine is free to round the specified * value up or down as it sees fit (or to ignore it completely). * * Specifying a value of zero for the `stackSize` parameter will * cause this constructor to behave exactly like the * `Thread(ThreadGroup, Runnable, String)` constructor. * * Due to the platform-dependent nature of the behavior of this * constructor, extreme care should be exercised in its use. * The thread stack size necessary to perform a given computation will * likely vary from one JRE implementation to another. In light of this * variation, careful tuning of the stack size parameter may be required, * and the tuning may need to be repeated for each JRE implementation on * which an application is to run. * * Implementation note: Java platform implementers are encouraged to * document their implementation's behavior with respect to the * `stackSize` parameter. * * * @param group * the thread group. If `null` and there is a security * manager, the group is determined by {@linkplain * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. * If there is not a security manager or ` * SecurityManager.getThreadGroup()` returns `null`, the group * is set to the current thread's thread group. * * @param target * the object whose `run` method is invoked when this thread * is started. If `null`, this thread's run method is invoked. * * @param name * the name of the new thread * * @param stackSize * the desired stack size for the new thread, or zero to indicate * that this parameter is to be ignored. * * @throws SecurityException * if the current thread cannot create a thread in the specified * thread group * * @since 1.4 */ constructor(group: ThreadGroup, target: Runnable, name: string, stackSize: number); /** * Allocates a new `Thread` object so that it has `target` * as its run object, has the specified `name` as its name, * belongs to the thread group referred to by `group`, has * the specified `stackSize`, and inherits initial values for * {@linkplain InheritableThreadLocal inheritable thread-local} variables * if `inheritThreadLocals` is `true`. * * This constructor is identical to {@link * #Thread(ThreadGroup,Runnable,String,long)} with the added ability to * suppress, or not, the inheriting of initial values for inheritable * thread-local variables from the constructing thread. This allows for * finer grain control over inheritable thread-locals. Care must be taken * when passing a value of `false` for `inheritThreadLocals`, * as it may lead to unexpected behavior if the new thread executes code * that expects a specific thread-local value to be inherited. * * Specifying a value of `true` for the `inheritThreadLocals` * parameter will cause this constructor to behave exactly like the * `Thread(ThreadGroup, Runnable, String, long)` constructor. * * @param group * the thread group. If `null` and there is a security * manager, the group is determined by {@linkplain * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. * If there is not a security manager or ` * SecurityManager.getThreadGroup()` returns `null`, the group * is set to the current thread's thread group. * * @param target * the object whose `run` method is invoked when this thread * is started. If `null`, this thread's run method is invoked. * * @param name * the name of the new thread * * @param stackSize * the desired stack size for the new thread, or zero to indicate * that this parameter is to be ignored * * @param inheritThreadLocals * if `true`, inherit initial values for inheritable * thread-locals from the constructing thread, otherwise no initial * values are inherited * * @throws SecurityException * if the current thread cannot create a thread in the specified * thread group * * @since 9 */ constructor(group: ThreadGroup, target: Runnable, name: string, stackSize: number, inheritThreadLocals: boolean); /** * Causes this thread to begin execution; the Java Virtual Machine * calls the `run` method of this thread. * * The result is that two threads are running concurrently: the * current thread (which returns from the call to the * `start` method) and the other thread (which executes its * `run` method). * * It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed * execution. * * @throws IllegalThreadStateException if the thread was already started. * @see #run() * @see #stop() */ start(): void; /** * If this thread was constructed using a separate * `Runnable` run object, then that * `Runnable` object's `run` method is called; * otherwise, this method does nothing and returns. * * Subclasses of `Thread` should override this method. * * @see #start() * @see #stop() * @see #Thread(ThreadGroup, Runnable, String) */ run(): void; /** * Forces the thread to stop executing. * * If there is a security manager installed, its `checkAccess` * method is called with `this` * as its argument. This may result in a * `SecurityException` being raised (in the current thread). * * If this thread is different from the current thread (that is, the current * thread is trying to stop a thread other than itself), the * security manager's `checkPermission` method (with a * `RuntimePermission("stopThread")` argument) is called in * addition. * Again, this may result in throwing a * `SecurityException` (in the current thread). * * The thread represented by this thread is forced to stop whatever * it is doing abnormally and to throw a newly created * `ThreadDeath` object as an exception. * * It is permitted to stop a thread that has not yet been started. * If the thread is eventually started, it immediately terminates. * * An application should not normally try to catch * `ThreadDeath` unless it must do some extraordinary * cleanup operation (note that the throwing of * `ThreadDeath` causes `finally` clauses of * `try` statements to be executed before the thread * officially dies). If a `catch` clause catches a * `ThreadDeath` object, it is important to rethrow the * object so that the thread actually dies. * * The top-level error handler that reacts to otherwise uncaught * exceptions does not print out a message or otherwise notify the * application if the uncaught exception is an instance of * `ThreadDeath`. * * @throws SecurityException if the current thread cannot * modify this thread. * @see #interrupt() * @see #checkAccess() * @see #run() * @see #start() * @see ThreadDeath * @see ThreadGroup#uncaughtException(Thread,Throwable) * @see SecurityManager#checkAccess(Thread) * @see SecurityManager#checkPermission * @deprecated This method is inherently unsafe. Stopping a thread with * Thread.stop causes it to unlock all of the monitors that it * has locked (as a natural consequence of the unchecked * `ThreadDeath` exception propagating up the stack). If * any of the objects previously protected by these monitors were in * an inconsistent state, the damaged objects become visible to * other threads, potentially resulting in arbitrary behavior. Many * uses of `stop` should be replaced by code that simply * modifies some variable to indicate that the target thread should * stop running. The target thread should check this variable * regularly, and return from its run method in an orderly fashion * if the variable indicates that it is to stop running. If the * target thread waits for long periods (on a condition variable, * for example), the `interrupt` method should be used to * interrupt the wait. * For more information, see * Why * are Thread.stop, Thread.suspend and Thread.resume Deprecated?. */ stop(): void; /** * Interrupts this thread. * * Unless the current thread is interrupting itself, which is * always permitted, the {@link #checkAccess() checkAccess} method * of this thread is invoked, which may cause a {@link * SecurityException} to be thrown. * * If this thread is blocked in an invocation of the {@link * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link * Object#wait(long, int) wait(long, int)} methods of the {@link Object} * class, or of the {@link #join()}, {@link #join(long)}, {@link * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)} * methods of this class, then its interrupt status will be cleared and it * will receive an {@link InterruptedException}. * * If this thread is blocked in an I/O operation upon an {@link * java.nio.channels.InterruptibleChannel InterruptibleChannel} * then the channel will be closed, the thread's interrupt * status will be set, and the thread will receive a {@link * java.nio.channels.ClosedByInterruptException}. * * If this thread is blocked in a {@link java.nio.channels.Selector} * then the thread's interrupt status will be set and it will return * immediately from the selection operation, possibly with a non-zero * value, just as if the selector's {@link * java.nio.channels.Selector#wakeup wakeup} method were invoked. * * If none of the previous conditions hold then this thread's interrupt * status will be set. * * Interrupting a thread that is not alive need not have any effect. * * @implNote In the JDK Reference Implementation, interruption of a thread * that is not alive still records that the interrupt request was made and * will report it via {@link #interrupted} and {@link #isInterrupted()}. * * @throws SecurityException * if the current thread cannot modify this thread * * @revised 6.0, 14 */ interrupt(): void; /** * Tests whether the current thread has been interrupted. The * interrupted status of the thread is cleared by this method. In * other words, if this method were to be called twice in succession, the * second call would return false (unless the current thread were * interrupted again, after the first call had cleared its interrupted * status and before the second call had examined it). * * @return `true` if the current thread has been interrupted; * `false` otherwise. * @see #isInterrupted() * @revised 6.0, 14 */ static interrupted(): boolean; /** * Tests whether this thread has been interrupted. The interrupted * status of the thread is unaffected by this method. * * @return `true` if this thread has been interrupted; * `false` otherwise. * @see #interrupted() * @revised 6.0, 14 */ isInterrupted(): boolean; /** * Tests if this thread is alive. A thread is alive if it has * been started and has not yet died. * * @return `true` if this thread is alive; * `false` otherwise. */ isAlive(): boolean; /** * Suspends this thread. * * First, the `checkAccess` method of this thread is called * with no arguments. This may result in throwing a * `SecurityException `(in the current thread). * * If the thread is alive, it is suspended and makes no further * progress unless and until it is resumed. * * @throws SecurityException if the current thread cannot modify * this thread. * @see #checkAccess * @deprecated This method has been deprecated, as it is * inherently deadlock-prone. If the target thread holds a lock on the * monitor protecting a critical system resource when it is suspended, no * thread can access this resource until the target thread is resumed. If * the thread that would resume the target thread attempts to lock this * monitor prior to calling `resume`, deadlock results. Such * deadlocks typically manifest themselves as "frozen" processes. * For more information, see * Why * are Thread.stop, Thread.suspend and Thread.resume Deprecated?. */ suspend(): void; /** * Resumes a suspended thread. * * First, the `checkAccess` method of this thread is called * with no arguments. This may result in throwing a * `SecurityException` (in the current thread). * * If the thread is alive but suspended, it is resumed and is * permitted to make progress in its execution. * * @throws SecurityException if the current thread cannot modify this * thread. * @see #checkAccess * @see #suspend() * @deprecated This method exists solely for use with {@link #suspend}, * which has been deprecated because it is deadlock-prone. * For more information, see * Why * are Thread.stop, Thread.suspend and Thread.resume Deprecated?. */ resume(): void; /** * Changes the priority of this thread. * * First the `checkAccess` method of this thread is called * with no arguments. This may result in throwing a `SecurityException`. * * Otherwise, the priority of this thread is set to the smaller of * the specified `newPriority` and the maximum permitted * priority of the thread's thread group. * * @param newPriority priority to set this thread to * @throws IllegalArgumentException If the priority is not in the * range `MIN_PRIORITY` to * `MAX_PRIORITY`. * @throws SecurityException if the current thread cannot modify * this thread. * @see #getPriority * @see #checkAccess() * @see #getThreadGroup() * @see #MAX_PRIORITY * @see #MIN_PRIORITY * @see ThreadGroup#getMaxPriority() */ set priority(priority: number); /** * Returns this thread's priority. * * @return this thread's priority. * @see #setPriority */ get priority(): number; /** * Changes the name of this thread to be equal to the argument `name`. * * First the `checkAccess` method of this thread is called * with no arguments. This may result in throwing a * `SecurityException`. * * @param name the new name for this thread. * @throws SecurityException if the current thread cannot modify this * thread. * @see #getName * @see #checkAccess() */ set name(name: string); /** * Returns this thread's name. * * @return this thread's name. * @see #setName(String) */ get name(): string; /** * Returns the thread group to which this thread belongs. * This method returns null if this thread has died * (been stopped). * * @return this thread's thread group. */ get threadGroup(): ThreadGroup; /** * Returns an estimate of the number of active threads in the current * thread's {@linkplain java.lang.ThreadGroup thread group} and its * subgroups. Recursively iterates over all subgroups in the current * thread's thread group. * * The value returned is only an estimate because the number of * threads may change dynamically while this method traverses internal * data structures, and might be affected by the presence of certain * system threads. This method is intended primarily for debugging * and monitoring purposes. * * @return an estimate of the number of active threads in the current * thread's thread group and in any other thread group that * has the current thread's thread group as an ancestor */ static activeCount(): number; /** * Copies into the specified array every active thread in the current * thread's thread group and its subgroups. This method simply * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])} * method of the current thread's thread group. * * An application might use the {@linkplain #activeCount activeCount} * method to get an estimate of how big the array should be, however * if the array is too short to hold all the threads, the extra threads * are silently ignored. If it is critical to obtain every active * thread in the current thread's thread group and its subgroups, the * invoker should verify that the returned int value is strictly less * than the length of `tarray`. * * Due to the inherent race condition in this method, it is recommended * that the method only be used for debugging and monitoring purposes. * * @param tarray * an array into which to put the list of threads * * @return the number of threads put into the array * * @throws SecurityException * if {@link java.lang.ThreadGroup#checkAccess} determines that * the current thread cannot access its thread group */ static enumerate(tarray: Thread[]): number; /** * Throws `UnsupportedOperationException`. * * @return nothing * * @deprecated This method was originally designed to count the number of * stack frames but the results were never well-defined and it * depended on thread-suspension. * This method is subject to removal in a future version of Java SE. * @see StackWalker */ countStackFrames(): number; /** * Waits at most `millis` milliseconds for this thread to * die. A timeout of `0` means to wait forever. * * This implementation uses a loop of `this.wait` calls * conditioned on `this.isAlive`. As a thread terminates the * `this.notifyAll` method is invoked. It is recommended that * applications not use `wait`, `notify`, or * `notifyAll` on `Thread` instances. * * @param millis * the time to wait in milliseconds * * @throws IllegalArgumentException * if the value of `millis` is negative * * @throws InterruptedException * if any thread has interrupted the current thread. The * interrupted status of the current thread is * cleared when this exception is thrown. */ join(millis: number): void; /** * Waits at most `millis` milliseconds plus * `nanos` nanoseconds for this thread to die. * If both arguments are `0`, it means to wait forever. * * This implementation uses a loop of `this.wait` calls * conditioned on `this.isAlive`. As a thread terminates the * `this.notifyAll` method is invoked. It is recommended that * applications not use `wait`, `notify`, or * `notifyAll` on `Thread` instances. * * @param millis * the time to wait in milliseconds * * @param nanos * `0-999999` additional nanoseconds to wait * * @throws IllegalArgumentException * if the value of `millis` is negative, or the value * of `nanos` is not in the range `0-999999` * * @throws InterruptedException * if any thread has interrupted the current thread. The * interrupted status of the current thread is * cleared when this exception is thrown. */ join(millis: number, nanos: number): void; /** * Waits for this thread to die. * * An invocation of this method behaves in exactly the same * way as the invocation * * * {@linkplain #join(long) join}`(0)` * * * @throws InterruptedException * if any thread has interrupted the current thread. The * interrupted status of the current thread is * cleared when this exception is thrown. */ join(): void; /** * Prints a stack trace of the current thread to the standard error stream. * This method is used only for debugging. */ static dumpStack(): void; /** * Marks this thread as either a {@linkplain #isDaemon daemon} thread * or a user thread. The Java Virtual Machine exits when the only * threads running are all daemon threads. * * This method must be invoked before the thread is started. * * @param on * if `true`, marks this thread as a daemon thread * * @throws IllegalThreadStateException * if this thread is {@linkplain #isAlive alive} * * @throws SecurityException * if {@link #checkAccess} determines that the current * thread cannot modify this thread */ setDaemon(on: boolean): void; /** * Tests if this thread is a daemon thread. * * @return `true` if this thread is a daemon thread; * `false` otherwise. * @see #setDaemon(boolean) */ isDaemon(): boolean; /** * Determines if the currently running thread has permission to * modify this thread. * * If there is a security manager, its `checkAccess` method * is called with this thread as its argument. This may result in * throwing a `SecurityException`. * * @throws SecurityException if the current thread is not allowed to * access this thread. * @see SecurityManager#checkAccess(Thread) */ checkAccess(): void; /** * Returns a string representation of this thread, including the * thread's name, priority, and thread group. * * @return a string representation of this thread. */ toString(): string; /** * Returns the context `ClassLoader` for this thread. The context * `ClassLoader` is provided by the creator of the thread for use * by code running in this thread when loading classes and resources. * If not {@linkplain #setContextClassLoader set}, the default is the * `ClassLoader` context of the parent thread. The context * `ClassLoader` of the * primordial thread is typically set to the class loader used to load the * application. * * * @return the context `ClassLoader` for this thread, or `null` * indicating the system class loader (or, failing that, the * bootstrap class loader) * * @throws SecurityException * if a security manager is present, and the caller's class loader * is not `null` and is not the same as or an ancestor of the * context class loader, and the caller does not have the * {@link RuntimePermission}`("getClassLoader")` * * @since 1.2 */ get contextClassLoader(): ClassLoader; /** * Sets the context ClassLoader for this Thread. The context * ClassLoader can be set when a thread is created, and allows * the creator of the thread to provide the appropriate class loader, * through `getContextClassLoader`, to code running in the thread * when loading classes and resources. * * If a security manager is present, its {@link * SecurityManager#checkPermission(java.security.Permission) checkPermission} * method is invoked with a {@link RuntimePermission RuntimePermission}` * ("setContextClassLoader")` permission to see if setting the context * ClassLoader is permitted. * * @param cl * the context ClassLoader for this Thread, or null indicating the * system class loader (or, failing that, the bootstrap class loader) * * @throws SecurityException * if the current thread cannot set the context ClassLoader * * @since 1.2 */ set contextClassLoader(contextClassLoader: ClassLoader); /** * Returns `true` if and only if the current thread holds the * monitor lock on the specified object. * * This method is designed to allow a program to assert that * the current thread already holds a specified lock: * * assert Thread.holdsLock(obj); * * * @param obj the object on which to test lock ownership * @throws NullPointerException if obj is `null` * @return `true` if the current thread holds the monitor lock on * the specified object. * @since 1.4 */ static holdsLock(obj: any): boolean; /** * Returns an array of stack trace elements representing the stack dump * of this thread. This method will return a zero-length array if * this thread has not started, has started but has not yet been * scheduled to run by the system, or has terminated. * If the returned array is of non-zero length then the first element of * the array represents the top of the stack, which is the most recent * method invocation in the sequence. The last element of the array * represents the bottom of the stack, which is the least recent method * invocation in the sequence. * * If there is a security manager, and this thread is not * the current thread, then the security manager's * `checkPermission` method is called with a * `RuntimePermission("getStackTrace")` permission * to see if it's ok to get the stack trace. * * Some virtual machines may, under some circumstances, omit one * or more stack frames from the stack trace. In the extreme case, * a virtual machine that has no stack trace information concerning * this thread is permitted to return a zero-length array from this * method. * * @return an array of `StackTraceElement`, * each represents one stack frame. * * @throws SecurityException * if a security manager exists and its * `checkPermission` method doesn't allow * getting the stack trace of thread. * @see SecurityManager#checkPermission * @see RuntimePermission * @see Throwable#getStackTrace * * @since 1.5 */ get stackTrace(): StackTraceElement[]; /** * Returns a map of stack traces for all live threads. * The map keys are threads and each map value is an array of * `StackTraceElement` that represents the stack dump * of the corresponding `Thread`. * The returned stack traces are in the format specified for * the {@link #getStackTrace getStackTrace} method. * * The threads may be executing while this method is called. * The stack trace of each thread only represents a snapshot and * each stack trace may be obtained at different time. A zero-length * array will be returned in the map value if the virtual machine has * no stack trace information about a thread. * * If there is a security manager, then the security manager's * `checkPermission` method is called with a * `RuntimePermission("getStackTrace")` permission as well as * `RuntimePermission("modifyThreadGroup")` permission * to see if it is ok to get the stack trace of all threads. * * @return a `Map` from `Thread` to an array of * `StackTraceElement` that represents the stack trace of * the corresponding thread. * * @throws SecurityException * if a security manager exists and its * `checkPermission` method doesn't allow * getting the stack trace of thread. * @see #getStackTrace * @see SecurityManager#checkPermission * @see RuntimePermission * @see Throwable#getStackTrace * * @since 1.5 */ static get allStackTraces(): Map; /** * Returns the identifier of this Thread. The thread ID is a positive * `long` number generated when this thread was created. * The thread ID is unique and remains unchanged during its lifetime. * When a thread is terminated, this thread ID may be reused. * * @return this thread's ID. * @since 1.5 */ get id(): number; /** * Returns the state of this thread. * This method is designed for use in monitoring of the system state, * not for synchronization control. * * @return this thread's state. * @since 1.5 */ get state(): State; /** * Set the default handler invoked when a thread abruptly terminates * due to an uncaught exception, and no other handler has been defined * for that thread. * * Uncaught exception handling is controlled first by the thread, then * by the thread's {@link ThreadGroup} object and finally by the default * uncaught exception handler. If the thread does not have an explicit * uncaught exception handler set, and the thread's thread group * (including parent thread groups) does not specialize its * `uncaughtException` method, then the default handler's * `uncaughtException` method will be invoked. * By setting the default uncaught exception handler, an application * can change the way in which uncaught exceptions are handled (such as * logging to a specific device, or file) for those threads that would * already accept whatever "default" behavior the system * provided. * * Note that the default uncaught exception handler should not usually * defer to the thread's `ThreadGroup` object, as that could cause * infinite recursion. * * @param eh the object to use as the default uncaught exception handler. * If `null` then there is no default handler. * * @throws SecurityException if a security manager is present and it denies * {@link RuntimePermission}`("setDefaultUncaughtExceptionHandler")` * * @see #setUncaughtExceptionHandler * @see #getUncaughtExceptionHandler * @see ThreadGroup#uncaughtException * @since 1.5 */ static set defaultUncaughtExceptionHandler(defaultUncaughtExceptionHandler: UncaughtExceptionHandler); /** * Returns the default handler invoked when a thread abruptly terminates * due to an uncaught exception. If the returned value is `null`, * there is no default. * @since 1.5 * @see #setDefaultUncaughtExceptionHandler * @return the default uncaught exception handler for all threads */ static get defaultUncaughtExceptionHandler(): UncaughtExceptionHandler; /** * Returns the handler invoked when this thread abruptly terminates * due to an uncaught exception. If this thread has not had an * uncaught exception handler explicitly set then this thread's * `ThreadGroup` object is returned, unless this thread * has terminated, in which case `null` is returned. * @since 1.5 * @return the uncaught exception handler for this thread */ get uncaughtExceptionHandler(): UncaughtExceptionHandler; /** * Set the handler invoked when this thread abruptly terminates * due to an uncaught exception. * A thread can take full control of how it responds to uncaught * exceptions by having its uncaught exception handler explicitly set. * If no such handler is set then the thread's `ThreadGroup` * object acts as its handler. * @param eh the object to use as this thread's uncaught exception * handler. If `null` then this thread has no explicit handler. * @throws SecurityException if the current thread is not allowed to * modify this thread. * @see #setDefaultUncaughtExceptionHandler * @see ThreadGroup#uncaughtException * @since 1.5 */ set uncaughtExceptionHandler(uncaughtExceptionHandler: UncaughtExceptionHandler); } export class InheritableThreadLocal extends ThreadLocal { /** * Creates an inheritable thread local variable. */ constructor(); } /** * The `Compiler` class is provided to support Java-to-native-code * compilers and related services. By design, the `Compiler` class does * nothing; it serves as a placeholder for a JIT compiler implementation. * If no compiler is available, these methods do nothing. * * @deprecated JIT compilers and their technologies vary too widely to * be controlled effectively by a standardized interface. As such, many * JIT compiler implementations ignore this interface, and are instead * controllable by implementation-specific mechanisms such as command-line * options. This class is subject to removal in a future version of Java SE. * * @author Frank Yellin * @since 1.0 */ export class Compiler { /** * Compiles the specified class. * * @param clazz * A class * * @return `true` if the compilation succeeded; `false` if the * compilation failed or no compiler is available * * @throws NullPointerException * If `clazz` is `null` */ static compileClass(clazz: Class): boolean; /** * Compiles all classes whose name matches the specified string. * * @param string * The name of the classes to compile * * @return `true` if the compilation succeeded; `false` if the * compilation failed or no compiler is available * * @throws NullPointerException * If `string` is `null` */ static compileClasses(string: string): boolean; /** * Examines the argument type and its fields and perform some documented * operation. No specific operations are required. * * @param any * An argument * * @return A compiler-specific value, or `null` if no compiler is * available * * @throws NullPointerException * If `any` is `null` */ static command(any: any): any; /** * Cause the Compiler to resume operation. */ static enable(): void; /** * Cause the Compiler to cease operation. */ static disable(): void; } /** * Subclasses of `LinkageError` indicate that a class has * some dependency on another class; however, the latter class has * incompatibly changed after the compilation of the former class. * * * @author Frank Yellin * @since 1.0 */ export class LinkageError extends Error { /** * Constructs a `LinkageError` with no detail message. */ constructor(); /** * Constructs a `LinkageError` with the specified detail * message. * * @param s the detail message. */ constructor(s: string); /** * Constructs a `LinkageError` with the specified detail * message and cause. * * @param s the detail message. * @param cause the cause, may be `null` * @since 1.7 */ constructor(s: string, cause: Throwable); } export class CharSequence { /** * Returns the length of this character sequence. The length is the number * of 16-bit `char`s in the sequence. * * @return the number of `char`s in this sequence */ length(): number; /** * Returns the `char` value at the specified index. An index ranges from zero * to `length() - 1`. The first `char` value of the sequence is at * index zero, the next at index one, and so on, as for array * indexing. * * If the `char` value specified by the index is a * surrogate, the surrogate * value is returned. * * @param index the index of the `char` value to be returned * * @return the specified `char` value * * @throws IndexOutOfBoundsException * if the `index` argument is negative or not less than * `length()` */ charAt(index: number): string; /** * Returns `true` if this character sequence is empty. * * @implSpec * The default implementation returns the result of calling `length() == 0`. * * @return `true` if {@link #length()} is `0`, otherwise * `false` * * @since 15 */ isEmpty(): boolean; /** * Returns a `CharSequence` that is a subsequence of this sequence. * The subsequence starts with the `char` value at the specified index and * ends with the `char` value at index `end - 1`. The length * (in `char`s) of the * returned sequence is `end - start`, so if `start == end` * then an empty sequence is returned. * * @param start the start index, inclusive * @param end the end index, exclusive * * @return the specified subsequence * * @throws IndexOutOfBoundsException * if `start` or `end` are negative, * if `end` is greater than `length()`, * or if `start` is greater than `end` */ subSequence(start: number, end: number): CharSequence; /** * Returns a string containing the characters in this sequence in the same * order as this sequence. The length of the string will be the length of * this sequence. * * @return a string consisting of exactly this sequence of characters */ toString(): string; /** * Returns a stream of `int` zero-extending the `char` values * from this sequence. Any char which maps to a surrogate code * point is passed through uninterpreted. * * The stream binds to this sequence when the terminal stream operation * commences (specifically, for mutable sequences the spliterator for the * stream is late-binding). * If the sequence is modified during that operation then the result is * undefined. * * @return an IntStream of char values from this sequence * @since 1.8 */ chars(): IntStream; /** * Returns a stream of code point values from this sequence. Any surrogate * pairs encountered in the sequence are combined as if by {@linkplain * Character#toCodePoint Character.toCodePoint} and the result is passed * to the stream. Any other code units, including ordinary BMP characters, * unpaired surrogates, and undefined code units, are zero-extended to * `int` values which are then passed to the stream. * * The stream binds to this sequence when the terminal stream operation * commences (specifically, for mutable sequences the spliterator for the * stream is late-binding). * If the sequence is modified during that operation then the result is * undefined. * * @return an IntStream of Unicode code points from this sequence * @since 1.8 */ codePoints(): IntStream; /** * Compares two `CharSequence` instances lexicographically. Returns a * negative value, zero, or a positive value if the first sequence is lexicographically * less than, equal to, or greater than the second, respectively. * * * The lexicographical ordering of `CharSequence` is defined as follows. * Consider a `CharSequence` cs of length len to be a * sequence of char values, cs[0] to cs[len-1]. Suppose k * is the lowest index at which the corresponding char values from each sequence * differ. The lexicographic ordering of the sequences is determined by a numeric * comparison of the char values cs1[k] with cs2[k]. If there is * no such index k, the shorter sequence is considered lexicographically * less than the other. If the sequences have the same length, the sequences are * considered lexicographically equal. * * * @param cs1 the first `CharSequence` * @param cs2 the second `CharSequence` * * @return the value `0` if the two `CharSequence` are equal; * a negative integer if the first `CharSequence` * is lexicographically less than the second; or a * positive integer if the first `CharSequence` is * lexicographically greater than the second. * * @since 11 */ static compare(cs1: CharSequence, cs2: CharSequence): number; } /** * Indicates that the named compiler warnings should be suppressed in the * annotated element (and in all program elements contained in the annotated * element). Note that the set of warnings suppressed in a given element is * a superset of the warnings suppressed in all containing elements. For * example, if you annotate a class to suppress one warning and annotate a * method to suppress another, both warnings will be suppressed in the method. * However, note that if a warning is suppressed in a ` * module-info` file, the suppression applies to elements within the * file and not to types contained within the module. * * As a matter of style, programmers should always use this annotation * on the most deeply nested element where it is effective. If you want to * suppress a warning in a particular method, you should annotate that * method rather than its class. * * @author Josh Bloch * @since 1.5 * @jls 4.8 Raw Types * @jls 4.12.2 Variables of Reference Type * @jls 5.1.9 Unchecked Conversion * @jls 5.5 Casting Contexts * @jls 9.6.4.5 @SuppressWarnings */ export class SuppressWarnings { } /** * Thrown by `String` methods to indicate that an index is either negative * or greater than the size of the string. For some methods such as the * {@link String#charAt charAt} method, this exception also is thrown when the * index is equal to the size of the string. * * @see java.lang.String#charAt(int) * @since 1.0 */ export class StringIndexOutOfBoundsException extends IndexOutOfBoundsException { /** * Constructs a `StringIndexOutOfBoundsException` with no detail * message. */ constructor(); /** * Constructs a `StringIndexOutOfBoundsException` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); /** * Constructs a new `StringIndexOutOfBoundsException` class with an * argument indicating the illegal index. * * The index is included in this exception's detail message. The * exact presentation format of the detail message is unspecified. * * @param index the illegal index. */ constructor(index: number); } /** * Thrown when creating a {@linkplain ModuleLayer module layer} fails. * * @see ModuleLayer * @since 9 */ export class LayerInstantiationException extends RuntimeException { /** * Constructs a `LayerInstantiationException` with no detail message. */ constructor(); /** * Constructs a `LayerInstantiationException` with the given detail * message. * * @param msg * The detail message; can be `null` */ constructor(msg: string); /** * Constructs a `LayerInstantiationException` with the given cause. * * @param cause * The cause; can be `null` */ constructor(cause: Throwable); /** * Constructs a `LayerInstantiationException` with the given detail * message and cause. * * @param msg * The detail message; can be `null` * @param cause * The cause; can be `null` */ constructor(msg: string, cause: Throwable); } /** * Common superclass of exceptions thrown by reflective operations in * core reflection. * * @see LinkageError * @since 1.7 */ export class ReflectiveOperationException extends Exception { /** * Constructs a new exception with `null` as its detail * message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. */ constructor(); /** * Constructs a new exception with the specified detail message. * The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ constructor(message: string); /** * Constructs a new exception with the specified detail message * and cause. * * Note that the detail message associated with * `cause` is not automatically incorporated in * this exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ constructor(message: string, cause: Throwable); /** * Constructs a new exception with the specified cause and a detail * message of `(cause==null ? null : cause.toString())` (which * typically contains the class and detail message of `cause`). * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ constructor(cause: Throwable); } /** * Thrown to indicate that the code has attempted to cast an object * to a subclass of which it is not an instance. For example, the * following code generates a `ClassCastException`: * * Object x = new Integer(0); * System.out.println((String)x); * * * @since 1.0 */ export class ClassCastException extends RuntimeException { /** * Constructs a `ClassCastException` with no detail message. */ constructor(); /** * Constructs a `ClassCastException` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); } /** * Thrown when the "verifier" detects that a class file, * though well formed, contains some sort of internal inconsistency * or security problem. * * @since 1.0 */ export class VerifyError extends LinkageError { /** * Constructs an `VerifyError` with no detail message. */ constructor(); /** * Constructs an `VerifyError` with the specified detail message. * * @param s the detail message. */ constructor(s: string); } /** * A thread-safe, mutable sequence of characters. * A string buffer is like a {@link String}, but can be modified. At any * point in time it contains some particular sequence of characters, but * the length and content of the sequence can be changed through certain * method calls. * * String buffers are safe for use by multiple threads. The methods * are synchronized where necessary so that all the operations on any * particular instance behave as if they occur in some serial order * that is consistent with the order of the method calls made by each of * the individual threads involved. * * The principal operations on a `StringBuffer` are the * `append` and `insert` methods, which are * overloaded so as to accept data of any type. Each effectively * converts a given datum to a string and then appends or inserts the * characters of that string to the string buffer. The * `append` method always adds these characters at the end * of the buffer; the `insert` method adds the characters at * a specified point. * * For example, if `z` refers to a string buffer object * whose current contents are `"start"`, then * the method call `z.append("le")` would cause the string * buffer to contain `"startle"`, whereas * `z.insert(4, "le")` would alter the string buffer to * contain `"starlet"`. * * In general, if sb refers to an instance of a `StringBuffer`, * then `sb.append(x)` has the same effect as * `sb.insert(sb.length(), x)`. * * Whenever an operation occurs involving a source sequence (such as * appending or inserting from a source sequence), this class synchronizes * only on the string buffer performing the operation, not on the source. * Note that while `StringBuffer` is designed to be safe to use * concurrently from multiple threads, if the constructor or the * `append` or `insert` operation is passed a source sequence * that is shared across threads, the calling code must ensure * that the operation has a consistent and unchanging view of the source * sequence for the duration of the operation. * This could be satisfied by the caller holding a lock during the * operation's call, by using an immutable source sequence, or by not * sharing the source sequence across threads. * * Every string buffer has a capacity. As long as the length of the * character sequence contained in the string buffer does not exceed * the capacity, it is not necessary to allocate a new internal * buffer array. If the internal buffer overflows, it is * automatically made larger. * * Unless otherwise noted, passing a `null` argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * * As of release JDK 5, this class has been supplemented with an equivalent * class designed for use by a single thread, {@link StringBuilder}. The * `StringBuilder` class should generally be used in preference to * this one, as it supports all of the same operations but it is faster, as * it performs no synchronization. * * @apiNote * `StringBuffer` implements `Comparable` but does not override * {@link Object#equals equals}. Thus, the natural ordering of `StringBuffer` * is inconsistent with equals. Care should be exercised if `StringBuffer` * objects are used as keys in a `SortedMap` or elements in a `SortedSet`. * See {@link Comparable}, {@link java.util.SortedMap SortedMap}, or * {@link java.util.SortedSet SortedSet} for more information. * * @author Arthur van Hoff * @see java.lang.StringBuilder * @see java.lang.String * @since 1.0 */ export class StringBuffer extends Serializable { /** * Constructs a string buffer with no characters in it and an * initial capacity of 16 characters. */ constructor(); /** * Constructs a string buffer with no characters in it and * the specified initial capacity. * * @param capacity the initial capacity. * @throws NegativeArraySizeException if the `capacity` * argument is less than `0`. */ constructor(capacity: number); /** * Constructs a string buffer initialized to the contents of the * specified string. The initial capacity of the string buffer is * `16` plus the length of the string argument. * * @param str the initial contents of the buffer. */ constructor(str: string); /** * Constructs a string buffer that contains the same characters * as the specified `CharSequence`. The initial capacity of * the string buffer is `16` plus the length of the * `CharSequence` argument. * * @param seq the sequence to copy. * @since 1.5 */ constructor(seq: CharSequence); /** * Compares two `StringBuffer` instances lexicographically. This method * follows the same rules for lexicographical comparison as defined in the * {@linkplain java.lang.CharSequence#compare(java.lang.CharSequence, * java.lang.CharSequence) CharSequence.compare(this, another)} method. * * * For finer-grained, locale-sensitive String comparison, refer to * {@link java.text.Collator}. * * @implNote * This method synchronizes on `this`, the current object, but not * `StringBuffer another` with which `this StringBuffer` is compared. * * @param another the `StringBuffer` to be compared with * * @return the value `0` if this `StringBuffer` contains the same * character sequence as that of the argument `StringBuffer`; a negative integer * if this `StringBuffer` is lexicographically less than the * `StringBuffer` argument; or a positive integer if this `StringBuffer` * is lexicographically greater than the `StringBuffer` argument. * * @since 11 */ compareTo(another: StringBuffer): number; length(): number; capacity(): number; ensureCapacity(minimumCapacity: number): void; /** * @since 1.5 */ trimToSize(): void; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @see #length() */ setLength(length: number): void; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @see #length() */ charAt(index: number): string; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ codePointAt(index: number): number; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ codePointBefore(index: number): number; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ codePointCount(beginIndex: number, endIndex: number): number; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ offsetByCodePoints(index: number, codePointOffset: number): number; /** * @throws IndexOutOfBoundsException {@inheritDoc} */ getChars(srcBegin: number, srcEnd: number, dst: string[], dstBegin: number): void; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @see #length() */ setCharAt(index: number, ch: string): void; append(obj: any): StringBuffer; append(str: string): StringBuffer; /** * Appends the specified `StringBuffer` to this sequence. * * The characters of the `StringBuffer` argument are appended, * in order, to the contents of this `StringBuffer`, increasing the * length of this `StringBuffer` by the length of the argument. * If `sb` is `null`, then the four characters * `"null"` are appended to this `StringBuffer`. * * Let n be the length of the old character sequence, the one * contained in the `StringBuffer` just prior to execution of the * `append` method. Then the character at index k in * the new character sequence is equal to the character at index k * in the old character sequence, if k is less than n; * otherwise, it is equal to the character at index k-n in the * argument `sb`. * * This method synchronizes on `this`, the destination * object, but does not synchronize on the source (`sb`). * * @param sb the `StringBuffer` to append. * @return a reference to this object. * @since 1.4 */ append(sb: StringBuffer): StringBuffer; /** * Appends the specified `CharSequence` to this * sequence. * * The characters of the `CharSequence` argument are appended, * in order, increasing the length of this sequence by the length of the * argument. * * The result of this method is exactly the same as if it were an * invocation of this.append(s, 0, s.length()); * * This method synchronizes on `this`, the destination * object, but does not synchronize on the source (`s`). * * If `s` is `null`, then the four characters * `"null"` are appended. * * @param s the `CharSequence` to append. * @return a reference to this object. * @since 1.5 */ append(s: CharSequence): StringBuffer; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ append(s: CharSequence, start: number, end: number): StringBuffer; append(str: string[]): StringBuffer; /** * @throws IndexOutOfBoundsException {@inheritDoc} */ append(str: string[], offset: number, len: number): StringBuffer; append(b: boolean): StringBuffer; append(i: number): StringBuffer; /** * @since 1.5 */ appendCodePoint(codePoint: number): StringBuffer; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ delete(start: number, end: number): StringBuffer; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ deleteCharAt(index: number): StringBuffer; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ replace(start: number, end: number, str: string): StringBuffer; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ substring(start: number): string; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.4 */ subSequence(start: number, end: number): CharSequence; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ substring(start: number, end: number): string; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ insert(index: number, str: string[], offset: number, len: number): StringBuffer; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, obj: any): StringBuffer; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, str: string): StringBuffer; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, str: string[]): StringBuffer; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ insert(dstOffset: number, s: CharSequence): StringBuffer; /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ insert(dstOffset: number, s: CharSequence, start: number, end: number): StringBuffer; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, b: boolean): StringBuffer; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, i: number): StringBuffer; /** * @since 1.4 */ indexOf(str: string): number; /** * @since 1.4 */ indexOf(str: string, fromIndex: number): number; /** * @since 1.4 */ lastIndexOf(str: string): number; /** * @since 1.4 */ lastIndexOf(str: string, fromIndex: number): number; /** * @since 1.0.2 */ reverse(): StringBuffer; toString(): string; /** * Compares this object with the specified object for order. Returns a * negative integer, zero, or a positive integer as this object is less * than, equal to, or greater than the specified object. * * The implementor must ensure * `sgn(x.compareTo(y)) == -sgn(y.compareTo(x))` * for all `x` and `y`. (This * implies that `x.compareTo(y)` must throw an exception iff * `y.compareTo(x)` throws an exception.) * * The implementor must also ensure that the relation is transitive: * `(x.compareTo(y) > 0 && y.compareTo(z) > 0)` implies * `x.compareTo(z) > 0`. * * Finally, the implementor must ensure that `x.compareTo(y)==0` * implies that `sgn(x.compareTo(z)) == sgn(y.compareTo(z))`, for * all `z`. * * It is strongly recommended, but not strictly required that * `(x.compareTo(y)==0) == (x.equals(y))`. Generally speaking, any * class that implements the `Comparable` interface and violates * this condition should clearly indicate this fact. The recommended * language is "Note: this class has a natural ordering that is * inconsistent with equals." * * In the foregoing description, the notation * `sgn(`expression`)` designates the mathematical * signum function, which is defined to return one of `-1`, * `0`, or `1` according to whether the value of * expression is negative, zero, or positive, respectively. * * @param o the object to be compared. * @return a negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. * * @throws NullPointerException if the specified object is null * @throws ClassCastException if the specified object's type prevents it * from being compared to this object. */ compareTo(o: T): number; } export interface StringBuffer extends Serializable, Comparable, CharSequence {} /** * Thrown when an unknown but serious exception has occurred in the * Java Virtual Machine. * * @since 1.0 */ export class UnknownError extends VirtualMachineError { /** * Constructs an `UnknownError` with no detail message. */ constructor(); /** * Constructs an `UnknownError` with the specified detail * message. * * @param s the detail message. */ constructor(s: string); } export class Module extends AnnotatedElement { /** * Returns `true` if this module is a named module. * * @return `true` if this is a named module * * @see ClassLoader#getUnnamedModule() */ isNamed(): boolean; /** * Returns the module name or `null` if this module is an unnamed * module. * * @return The module name */ get name(): string; /** * Returns the `ClassLoader` for this module. * * If there is a security manager then its `checkPermission` * method if first called with a `RuntimePermission("getClassLoader")` * permission to check that the caller is allowed to get access to the * class loader. * * @return The class loader for this module * * @throws SecurityException * If denied by the security manager */ get classLoader(): ClassLoader; /** * Returns the module descriptor for this module or `null` if this * module is an unnamed module. * * @return The module descriptor for this module */ get descriptor(): ModuleDescriptor; /** * Returns the module layer that contains this module or `null` if * this module is not in a module layer. * * A module layer contains named modules and therefore this method always * returns `null` when invoked on an unnamed module. * * Dynamic modules are * named modules that are generated at runtime. A dynamic module may or may * not be in a module layer. * * @return The module layer that contains this module * * @see java.lang.reflect.Proxy */ get layer(): ModuleLayer; /** * Indicates if this module reads the given module. This method returns * `true` if invoked to test if this module reads itself. It also * returns `true` if invoked on an unnamed module (as unnamed * modules read all modules). * * @param other * The other module * * @return `true` if this module reads `other` * * @see #addReads(Module) */ canRead(other: Module): boolean; /** * If the caller's module is this module then update this module to read * the given module. * * This method is a no-op if `other` is this module (all modules read * themselves), this module is an unnamed module (as unnamed modules read * all modules), or this module already reads `other`. * * @implNote Read edges added by this method are weak and * do not prevent `other` from being GC'ed when this module is * strongly reachable. * * @param other * The other module * * @return this module * * @throws IllegalCallerException * If this is a named module and the caller's module is not this * module * * @see #canRead */ addReads(other: Module): Module; /** * Returns `true` if this module exports the given package to at * least the given module. * * This method returns `true` if invoked to test if a package in * this module is exported to itself. It always returns `true` when * invoked on an unnamed module. A package that is {@link #isOpen open} to * the given module is considered exported to that module at run-time and * so this method returns `true` if the package is open to the given * module. * * This method does not check if the given module reads this module. * * @param pn * The package name * @param other * The other module * * @return `true` if this module exports the package to at least the * given module * * @see ModuleDescriptor#exports() * @see #addExports(String,Module) */ isExported(pn: string, other: Module): boolean; /** * Returns `true` if this module has opened a package to at * least the given module. * * This method returns `true` if invoked to test if a package in * this module is open to itself. It returns `true` when invoked on an * {@link ModuleDescriptor#isOpen open} module with a package in the module. * It always returns `true` when invoked on an unnamed module. * * This method does not check if the given module reads this module. * * @param pn * The package name * @param other * The other module * * @return `true` if this module has opened the package * to at least the given module * * @see ModuleDescriptor#opens() * @see #addOpens(String,Module) * @see java.lang.reflect.AccessibleObject#setAccessible(boolean) * @see java.lang.invoke.MethodHandles#privateLookupIn */ isOpen(pn: string, other: Module): boolean; /** * Returns `true` if this module exports the given package * unconditionally. * * This method always returns `true` when invoked on an unnamed * module. A package that is {@link #isOpen(String) opened} unconditionally * is considered exported unconditionally at run-time and so this method * returns `true` if the package is opened unconditionally. * * This method does not check if the given module reads this module. * * @param pn * The package name * * @return `true` if this module exports the package unconditionally * * @see ModuleDescriptor#exports() */ isExported(pn: string): boolean; /** * Returns `true` if this module has opened a package * unconditionally. * * This method always returns `true` when invoked on an unnamed * module. Additionally, it always returns `true` when invoked on an * {@link ModuleDescriptor#isOpen open} module with a package in the * module. * * This method does not check if the given module reads this module. * * @param pn * The package name * * @return `true` if this module has opened the package * unconditionally * * @see ModuleDescriptor#opens() */ isOpen(pn: string): boolean; /** * If the caller's module is this module then update this module to export * the given package to the given module. * * This method has no effect if the package is already exported (or * open) to the given module. * * @apiNote As specified in section {@jvms 5.4.3} of the The Java * Virtual Machine Specification , if an attempt to resolve a * symbolic reference fails because of a linkage error, then subsequent * attempts to resolve the reference always fail with the same error that * was thrown as a result of the initial resolution attempt. * * @param pn * The package name * @param other * The module * * @return this module * * @throws IllegalArgumentException * If `pn` is `null`, or this is a named module and the * package `pn` is not a package in this module * @throws IllegalCallerException * If this is a named module and the caller's module is not this * module * * @jvms 5.4.3 Resolution * @see #isExported(String,Module) */ addExports(pn: string, other: Module): Module; /** * If this module has opened a package to at least the caller * module then update this module to open the package to the given module. * Opening a package with this method allows all types in the package, * and all their members, not just public types and their public members, * to be reflected on by the given module when using APIs that support * private access or a way to bypass or suppress default Java language * access control checks. * * This method has no effect if the package is already open * to the given module. * * @apiNote This method can be used for cases where a consumer * module uses a qualified opens to open a package to an API * module but where the reflective access to the members of classes in * the consumer module is delegated to code in another module. Code in the * API module can use this method to open the package in the consumer module * to the other module. * * @param pn * The package name * @param other * The module * * @return this module * * @throws IllegalArgumentException * If `pn` is `null`, or this is a named module and the * package `pn` is not a package in this module * @throws IllegalCallerException * If this is a named module and this module has not opened the * package to at least the caller's module * * @see #isOpen(String,Module) * @see java.lang.reflect.AccessibleObject#setAccessible(boolean) * @see java.lang.invoke.MethodHandles#privateLookupIn */ addOpens(pn: string, other: Module): Module; /** * If the caller's module is this module then update this module to add a * service dependence on the given service type. This method is intended * for use by frameworks that invoke {@link java.util.ServiceLoader * ServiceLoader} on behalf of other modules or where the framework is * passed a reference to the service type by other code. This method is * a no-op when invoked on an unnamed module or an automatic module. * * This method does not cause {@link Configuration#resolveAndBind * resolveAndBind} to be re-run. * * @param service * The service type * * @return this module * * @throws IllegalCallerException * If this is a named module and the caller's module is not this * module * * @see #canUse(Class) * @see ModuleDescriptor#uses() */ addUses(service: Class): Module; /** * Indicates if this module has a service dependence on the given service * type. This method always returns `true` when invoked on an unnamed * module or an automatic module. * * @param service * The service type * * @return `true` if this module uses service type `st` * * @see #addUses(Class) */ canUse(service: Class): boolean; /** * Returns the set of package names for the packages in this module. * * For named modules, the returned set contains an element for each * package in the module. * * For unnamed modules, the returned set contains an element for * each package that {@link ClassLoader#getDefinedPackages() has been defined} * in the unnamed module. * * @return the set of the package names of the packages in this module */ get packages(): Set; /** * {@inheritDoc} * This method returns `null` when invoked on an unnamed module. * * Note that any annotation returned by this method is a * declaration annotation. */ getAnnotation(annotationClass: Class): T; /** * {@inheritDoc} * This method returns an empty array when invoked on an unnamed module. * * Note that any annotations returned by this method are * declaration annotations. */ get annotations(): Annotation[]; /** * {@inheritDoc} * This method returns an empty array when invoked on an unnamed module. * * Note that any annotations returned by this method are * declaration annotations. */ get declaredAnnotations(): Annotation[]; /** * Returns an input stream for reading a resource in this module. * The `name` parameter is a `'/'`-separated path name that * identifies the resource. As with {@link Class#getResourceAsStream * Class.getResourceAsStream}, this method delegates to the module's class * loader {@link ClassLoader#findResource(String,String) * findResource(String,String)} method, invoking it with the module name * (or `null` when the module is unnamed) and the name of the * resource. If the resource name has a leading slash then it is dropped * before delegation. * * A resource in a named module may be encapsulated so that * it cannot be located by code in other modules. Whether a resource can be * located or not is determined as follows: * * * If the resource name ends with "`.class`" then it is not * encapsulated. * * A package name is derived from the resource name. If * the package name is a {@linkplain #getPackages() package} in the * module then the resource can only be located by the caller of this * method when the package is {@linkplain #isOpen(String,Module) open} * to at least the caller's module. If the resource is not in a * package in the module then the resource is not encapsulated. * * * In the above, the package name for a resource is derived * from the subsequence of characters that precedes the last `'/'` in * the name and then replacing each `'/'` character in the subsequence * with `'.'`. A leading slash is ignored when deriving the package * name. As an example, the package name derived for a resource named * "`a/b/c/foo.properties`" is "`a.b.c`". A resource name * with the name "`META-INF/MANIFEST.MF`" is never encapsulated * because "`META-INF`" is not a legal package name. * * This method returns `null` if the resource is not in this * module, the resource is encapsulated and cannot be located by the caller, * or access to the resource is denied by the security manager. * * @param name * The resource name * * @return An input stream for reading the resource or `null` * * @throws IOException * If an I/O error occurs * * @see Class#getResourceAsStream(String) */ getResourceAsStream(name: string): InputStream; /** * Returns the string representation of this module. For a named module, * the representation is the string `"module"`, followed by a space, * and then the module name. For an unnamed module, the representation is * the string `"unnamed module"`, followed by a space, and then an * implementation specific string that identifies the unnamed module. * * @return The string representation of this module */ toString(): string; } /** * Thrown if an application tries to access or modify a specified * field of an object, and that object no longer has that field. * * Normally, this error is caught by the compiler; this error can * only occur at run time if the definition of a class has * incompatibly changed. * * @since 1.0 */ export class NoSuchFieldError extends IncompatibleClassChangeError { /** * Constructs a `NoSuchFieldError` with no detail message. */ constructor(); /** * Constructs a `NoSuchFieldError` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); } /** * A `Readable` is a source of characters. Characters from * a `Readable` are made available to callers of the read * method via a {@link java.nio.CharBuffer CharBuffer}. * * @since 1.5 */ export class Readable { /** * Attempts to read characters into the specified character buffer. * The buffer is used as a repository of characters as-is: the only * changes made are the results of a put operation. No flipping or * rewinding of the buffer is performed. * * @param cb the buffer to read characters into * @return The number of `char` values added to the buffer, * or -1 if this source of characters is at its end * @throws IOException if an I/O error occurs * @throws NullPointerException if cb is null * @throws java.nio.ReadOnlyBufferException if cb is a read only buffer */ read(cb: CharBuffer): number; } /** * Thrown by the security manager to indicate a security violation. * * @see java.lang.SecurityManager * @since 1.0 */ export class SecurityException extends RuntimeException { /** * Constructs a `SecurityException` with no detail message. */ constructor(); /** * Constructs a `SecurityException` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); /** * Creates a `SecurityException` with the specified * detail message and cause. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ constructor(message: string, cause: Throwable); /** * Creates a `SecurityException` with the specified cause * and a detail message of `(cause==null ? null : cause.toString())` * (which typically contains the class and detail message of * `cause`). * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ constructor(cause: Throwable); } /** * `Process` provides control of native processes started by * ProcessBuilder.start and Runtime.exec. * The class provides methods for performing input from the process, performing * output to the process, waiting for the process to complete, * checking the exit status of the process, and destroying (killing) * the process. * The {@link ProcessBuilder#start()} and * {@link Runtime#exec(String[],String[],File) Runtime.exec} * methods create a native process and return an instance of a * subclass of `Process` that can be used to control the process * and obtain information about it. * * The methods that create processes may not work well for special * processes on certain native platforms, such as native windowing * processes, daemon processes, Win16/DOS processes on Microsoft * Windows, or shell scripts. * * By default, the created process does not have its own terminal * or console. All its standard I/O (i.e. stdin, stdout, stderr) * operations will be redirected to the parent process, where they can * be accessed via the streams obtained using the methods * {@link #getOutputStream()}, * {@link #getInputStream()}, and * {@link #getErrorStream()}. * The parent process uses these streams to feed input to and get output * from the process. Because some native platforms only provide * limited buffer size for standard input and output streams, failure * to promptly write the input stream or read the output stream of * the process may cause the process to block, or even deadlock. * * Where desired, * process I/O can also be redirected * using methods of the {@link ProcessBuilder} class. * * The process is not killed when there are no more references to * the `Process` object, but rather the process * continues executing asynchronously. * * There is no requirement that the process represented by a ` * Process` object execute asynchronously or concurrently with respect * to the Java process that owns the `Process` object. * * As of 1.5, {@link ProcessBuilder#start()} is the preferred way * to create a `Process`. * * Subclasses of Process should override the {@link #onExit()} and * {@link #toHandle()} methods to provide a fully functional Process including the * {@linkplain #pid() process id}, * {@linkplain #info() information about the process}, * {@linkplain #children() direct children}, and * {@linkplain #descendants() direct children plus descendants of those children} of the process. * Delegating to the underlying Process or ProcessHandle is typically * easiest and most efficient. * * @since 1.0 */ export class Process { /** * Default constructor for Process. */ constructor(); /** * Returns the output stream connected to the normal input of the * process. Output to the stream is piped into the standard * input of the process represented by this `Process` object. * * If the standard input of the process has been redirected using * {@link ProcessBuilder#redirectInput(Redirect) * ProcessBuilder.redirectInput} * then this method will return a * null output stream. * * Implementation note: It is a good idea for the returned * output stream to be buffered. * * @return the output stream connected to the normal input of the * process */ get outputStream(): OutputStream; /** * Returns the input stream connected to the normal output of the * process. The stream obtains data piped from the standard * output of the process represented by this `Process` object. * * If the standard output of the process has been redirected using * {@link ProcessBuilder#redirectOutput(Redirect) * ProcessBuilder.redirectOutput} * then this method will return a * null input stream. * * Otherwise, if the standard error of the process has been * redirected using * {@link ProcessBuilder#redirectErrorStream(boolean) * ProcessBuilder.redirectErrorStream} * then the input stream returned by this method will receive the * merged standard output and the standard error of the process. * * Implementation note: It is a good idea for the returned * input stream to be buffered. * * @return the input stream connected to the normal output of the * process */ get inputStream(): InputStream; /** * Returns the input stream connected to the error output of the * process. The stream obtains data piped from the error output * of the process represented by this `Process` object. * * If the standard error of the process has been redirected using * {@link ProcessBuilder#redirectError(Redirect) * ProcessBuilder.redirectError} or * {@link ProcessBuilder#redirectErrorStream(boolean) * ProcessBuilder.redirectErrorStream} * then this method will return a * null input stream. * * Implementation note: It is a good idea for the returned * input stream to be buffered. * * @return the input stream connected to the error output of * the process */ get errorStream(): InputStream; /** * Causes the current thread to wait, if necessary, until the * process represented by this `Process` object has * terminated. This method returns immediately if the process * has already terminated. If the process has not yet * terminated, the calling thread will be blocked until the * process exits. * * @return the exit value of the process represented by this * `Process` object. By convention, the value * `0` indicates normal termination. * @throws InterruptedException if the current thread is * {@linkplain Thread#interrupt() interrupted} by another * thread while it is waiting, then the wait is ended and * an {@link InterruptedException} is thrown. */ waitFor(): number; /** * Causes the current thread to wait, if necessary, until the * process represented by this `Process` object has * terminated, or the specified waiting time elapses. * * If the process has already terminated then this method returns * immediately with the value `true`. If the process has not * terminated and the timeout value is less than, or equal to, zero, then * this method returns immediately with the value `false`. * * The default implementation of this methods polls the `exitValue` * to check if the process has terminated. Concrete implementations of this * class are strongly encouraged to override this method with a more * efficient implementation. * * @param timeout the maximum time to wait * @param unit the time unit of the `timeout` argument * @return `true` if the process has exited and `false` if * the waiting time elapsed before the process has exited. * @throws InterruptedException if the current thread is interrupted * while waiting. * @throws NullPointerException if unit is null * @since 1.8 */ waitFor(timeout: number, unit: TimeUnit): boolean; /** * Returns the exit value for the process. * * @return the exit value of the process represented by this * `Process` object. By convention, the value * `0` indicates normal termination. * @throws IllegalThreadStateException if the process represented * by this `Process` object has not yet terminated */ exitValue(): number; /** * Kills the process. * Whether the process represented by this `Process` object is * {@linkplain #supportsNormalTermination normally terminated} or not is * implementation dependent. * Forcible process destruction is defined as the immediate termination of a * process, whereas normal termination allows the process to shut down cleanly. * If the process is not alive, no action is taken. * * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is * {@linkplain java.util.concurrent.CompletableFuture#complete completed} * when the process has terminated. */ destroy(): void; /** * Kills the process forcibly. The process represented by this * `Process` object is forcibly terminated. * Forcible process destruction is defined as the immediate termination of a * process, whereas normal termination allows the process to shut down cleanly. * If the process is not alive, no action is taken. * * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is * {@linkplain java.util.concurrent.CompletableFuture#complete completed} * when the process has terminated. * * Invoking this method on `Process` objects returned by * {@link ProcessBuilder#start} and {@link Runtime#exec} forcibly terminate * the process. * * @implSpec * The default implementation of this method invokes {@link #destroy} * and so may not forcibly terminate the process. * @implNote * Concrete implementations of this class are strongly encouraged to override * this method with a compliant implementation. * @apiNote * The process may not terminate immediately. * i.e. `isAlive()` may return true for a brief period * after `destroyForcibly()` is called. This method * may be chained to `waitFor()` if needed. * * @return the `Process` object representing the * process forcibly destroyed * @since 1.8 */ destroyForcibly(): Process; /** * Returns `true` if the implementation of {@link #destroy} is to * normally terminate the process, * Returns `false` if the implementation of `destroy` * forcibly and immediately terminates the process. * * Invoking this method on `Process` objects returned by * {@link ProcessBuilder#start} and {@link Runtime#exec} return * `true` or `false` depending on the platform implementation. * * @implSpec * This implementation throws an instance of * {@link java.lang.UnsupportedOperationException} and performs no other action. * * @return `true` if the implementation of {@link #destroy} is to * normally terminate the process; * otherwise, {@link #destroy} forcibly terminates the process * @throws UnsupportedOperationException if the Process implementation * does not support this operation * @since 9 */ supportsNormalTermination(): boolean; /** * Tests whether the process represented by this `Process` is * alive. * * @return `true` if the process represented by this * `Process` object has not yet terminated. * @since 1.8 */ isAlive(): boolean; /** * Returns the native process ID of the process. * The native process ID is an identification number that the operating * system assigns to the process. * * @implSpec * The implementation of this method returns the process id as: * {@link #toHandle toHandle().pid()}. * * @return the native process id of the process * @throws UnsupportedOperationException if the Process implementation * does not support this operation * @since 9 */ pid(): number; /** * Returns a `CompletableFuture` for the termination of the Process. * The {@link java.util.concurrent.CompletableFuture} provides the ability * to trigger dependent functions or actions that may be run synchronously * or asynchronously upon process termination. * When the process has terminated the CompletableFuture is * {@link java.util.concurrent.CompletableFuture#complete completed} regardless * of the exit status of the process. * * Calling `onExit().get()` waits for the process to terminate and returns * the Process. The future can be used to check if the process is * {@linkplain java.util.concurrent.CompletableFuture#isDone done} or to * {@linkplain java.util.concurrent.CompletableFuture#get() wait} for it to terminate. * {@linkplain java.util.concurrent.CompletableFuture#cancel(boolean) Cancelling} * the CompletableFuture does not affect the Process. * * Processes returned from {@link ProcessBuilder#start} override the * default implementation to provide an efficient mechanism to wait * for process exit. * * @apiNote * Using {@link #onExit() onExit} is an alternative to * {@link #waitFor() waitFor} that enables both additional concurrency * and convenient access to the result of the Process. * Lambda expressions can be used to evaluate the result of the Process * execution. * If there is other processing to be done before the value is used * then {@linkplain #onExit onExit} is a convenient mechanism to * free the current thread and block only if and when the value is needed. * * For example, launching a process to compare two files and get a boolean if they are identical: * {@code Process p = new ProcessBuilder("cmp", "f1", "f2").start(); * Future identical = p.onExit().thenApply(p1 -> p1.exitValue() == 0); * ... * if (identical.get()) { ... } * } * * @implSpec * This implementation executes {@link #waitFor()} in a separate thread * repeatedly until it returns successfully. If the execution of * `waitFor` is interrupted, the thread's interrupt status is preserved. * * When {@link #waitFor()} returns successfully the CompletableFuture is * {@linkplain java.util.concurrent.CompletableFuture#complete completed} regardless * of the exit status of the process. * * This implementation may consume a lot of memory for thread stacks if a * large number of processes are waited for concurrently. * * External implementations should override this method and provide * a more efficient implementation. For example, to delegate to the underlying * process, it can do the following: * {@code * public CompletableFuture onExit() { * return delegate.onExit().thenApply(p -> this); * } * } * @apiNote * The process may be observed to have terminated with {@link #isAlive} * before the ComputableFuture is completed and dependent actions are invoked. * * @return a new `CompletableFuture` for the Process * * @since 9 */ onExit(): CompletableFuture; /** * Returns a ProcessHandle for the Process. * * `Process` objects returned by {@link ProcessBuilder#start} and * {@link Runtime#exec} implement `toHandle` as the equivalent of * {@link ProcessHandle#of(long) ProcessHandle.of(pid)} including the * check for a SecurityManager and `RuntimePermission("manageProcess")`. * * @implSpec * This implementation throws an instance of * {@link java.lang.UnsupportedOperationException} and performs no other action. * Subclasses should override this method to provide a ProcessHandle for the * process. The methods {@link #pid}, {@link #info}, {@link #children}, * and {@link #descendants}, unless overridden, operate on the ProcessHandle. * * @return Returns a ProcessHandle for the Process * @throws UnsupportedOperationException if the Process implementation * does not support this operation * @throws SecurityException if a security manager has been installed and * it denies RuntimePermission("manageProcess") * @since 9 */ toHandle(): ProcessHandle; /** * Returns a snapshot of information about the process. * * A {@link ProcessHandle.Info} instance has accessor methods * that return information about the process if it is available. * * @implSpec * This implementation returns information about the process as: * {@link #toHandle toHandle().info()}. * * @return a snapshot of information about the process, always non-null * @throws UnsupportedOperationException if the Process implementation * does not support this operation * @since 9 */ info(): Info; /** * Returns a snapshot of the direct children of the process. * The parent of a direct child process is the process. * Typically, a process that is {@linkplain #isAlive not alive} has no children. * * Note that processes are created and terminate asynchronously. * There is no guarantee that a process is {@linkplain #isAlive alive}. * * * @implSpec * This implementation returns the direct children as: * {@link #toHandle toHandle().children()}. * * @return a sequential Stream of ProcessHandles for processes that are * direct children of the process * @throws UnsupportedOperationException if the Process implementation * does not support this operation * @throws SecurityException if a security manager has been installed and * it denies RuntimePermission("manageProcess") * @since 9 */ children(): Stream; /** * Returns a snapshot of the descendants of the process. * The descendants of a process are the children of the process * plus the descendants of those children, recursively. * Typically, a process that is {@linkplain #isAlive not alive} has no children. * * Note that processes are created and terminate asynchronously. * There is no guarantee that a process is {@linkplain #isAlive alive}. * * * @implSpec * This implementation returns all children as: * {@link #toHandle toHandle().descendants()}. * * @return a sequential Stream of ProcessHandles for processes that * are descendants of the process * @throws UnsupportedOperationException if the Process implementation * does not support this operation * @throws SecurityException if a security manager has been installed and * it denies RuntimePermission("manageProcess") * @since 9 */ descendants(): Stream; } /** * Thrown if an application attempts to access or modify a field, or * to call a method that it does not have access to. * * Normally, this error is caught by the compiler; this error can * only occur at run time if the definition of a class has * incompatibly changed. * * @since 1.0 */ export class IllegalAccessError extends IncompatibleClassChangeError { /** * Constructs an `IllegalAccessError` with no detail message. */ constructor(); /** * Constructs an `IllegalAccessError` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); } /** * Thrown to indicate that an attempt has been made to store the * wrong type of object into an array of objects. For example, the * following code generates an `ArrayStoreException`: * * Object x[] = new String[3]; * x[0] = new Integer(0); * * * @since 1.0 */ export class ArrayStoreException extends RuntimeException { /** * Constructs an `ArrayStoreException` with no detail message. */ constructor(); /** * Constructs an `ArrayStoreException` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); } export class ModuleLayer { /** * Creates a new module layer, with this layer as its parent, by defining the * modules in the given `Configuration` to the Java virtual machine. * This method creates one class loader and defines all modules to that * class loader. The {@link ClassLoader#getParent() parent} of each class * loader is the given parent class loader. This method works exactly as * specified by the static {@link * #defineModulesWithOneLoader(Configuration,List,ClassLoader) * defineModulesWithOneLoader} method when invoked with this layer as the * parent. In other words, if this layer is `thisLayer` then this * method is equivalent to invoking: * {@code * ModuleLayer.defineModulesWithOneLoader(cf, List.of(thisLayer), parentLoader).layer(); * } * * @param cf * The configuration for the layer * @param parentLoader * The parent class loader for the class loader created by this * method; may be `null` for the bootstrap class loader * * @return The newly created layer * * @throws IllegalArgumentException * If the given configuration has more than one parent or the parent * of the configuration is not the configuration for this layer * @throws LayerInstantiationException * If the layer cannot be created for any of the reasons specified * by the static `defineModulesWithOneLoader` method * @throws SecurityException * If `RuntimePermission("createClassLoader")` or * `RuntimePermission("getClassLoader")` is denied by * the security manager * * @see #findLoader */ defineModulesWithOneLoader(cf: Configuration, parentLoader: ClassLoader): ModuleLayer; /** * Creates a new module layer, with this layer as its parent, by defining the * modules in the given `Configuration` to the Java virtual machine. * Each module is defined to its own {@link ClassLoader} created by this * method. The {@link ClassLoader#getParent() parent} of each class loader * is the given parent class loader. This method works exactly as specified * by the static {@link * #defineModulesWithManyLoaders(Configuration,List,ClassLoader) * defineModulesWithManyLoaders} method when invoked with this layer as the * parent. In other words, if this layer is `thisLayer` then this * method is equivalent to invoking: * {@code * ModuleLayer.defineModulesWithManyLoaders(cf, List.of(thisLayer), parentLoader).layer(); * } * * @param cf * The configuration for the layer * @param parentLoader * The parent class loader for each of the class loaders created by * this method; may be `null` for the bootstrap class loader * * @return The newly created layer * * @throws IllegalArgumentException * If the given configuration has more than one parent or the parent * of the configuration is not the configuration for this layer * @throws LayerInstantiationException * If the layer cannot be created for any of the reasons specified * by the static `defineModulesWithManyLoaders` method * @throws SecurityException * If `RuntimePermission("createClassLoader")` or * `RuntimePermission("getClassLoader")` is denied by * the security manager * * @see #findLoader */ defineModulesWithManyLoaders(cf: Configuration, parentLoader: ClassLoader): ModuleLayer; /** * Creates a new module layer, with this layer as its parent, by defining the * modules in the given `Configuration` to the Java virtual machine. * Each module is mapped, by name, to its class loader by means of the * given function. This method works exactly as specified by the static * {@link #defineModules(Configuration,List,Function) defineModules} * method when invoked with this layer as the parent. In other words, if * this layer is `thisLayer` then this method is equivalent to * invoking: * {@code * ModuleLayer.defineModules(cf, List.of(thisLayer), clf).layer(); * } * * @param cf * The configuration for the layer * @param clf * The function to map a module name to a class loader * * @return The newly created layer * * @throws IllegalArgumentException * If the given configuration has more than one parent or the parent * of the configuration is not the configuration for this layer * @throws LayerInstantiationException * If the layer cannot be created for any of the reasons specified * by the static `defineModules` method * @throws SecurityException * If `RuntimePermission("getClassLoader")` is denied by * the security manager */ defineModules(cf: Configuration, clf: Function): ModuleLayer; /** * Creates a new module layer by defining the modules in the given ` * Configuration` to the Java virtual machine. This method creates one * class loader and defines all modules to that class loader. * * The class loader created by this method implements direct * delegation when loading classes from modules. If the {@link * ClassLoader#loadClass(String, boolean) loadClass} method is invoked to * load a class then it uses the package name of the class to map it to a * module. This may be a module in this layer and hence defined to the same * class loader. It may be a package in a module in a parent layer that is * exported to one or more of the modules in this layer. The class * loader delegates to the class loader of the module, throwing ` * ClassNotFoundException` if not found by that class loader. * When `loadClass` is invoked to load classes that do not map to a * module then it delegates to the parent class loader. * * The class loader created by this method locates resources * ({@link ClassLoader#getResource(String) getResource}, {@link * ClassLoader#getResources(String) getResources}, and other resource * methods) in all modules in the layer before searching the parent class * loader. * * Attempting to create a layer with all modules defined to the same * class loader can fail for the following reasons: * * * * Overlapping packages: Two or more modules in the * configuration have the same package. * * Split delegation: The resulting class loader would * need to delegate to more than one class loader in order to load * classes in a specific package. * * * * In addition, a layer cannot be created if the configuration contains * a module named "`java.base`", or a module contains a package named * "`java`" or a package with a name starting with "`java.`". * * If there is a security manager then the class loader created by * this method will load classes and resources with privileges that are * restricted by the calling context of this method. * * @param cf * The configuration for the layer * @param parentLayers * The list of parent layers in search order * @param parentLoader * The parent class loader for the class loader created by this * method; may be `null` for the bootstrap class loader * * @return A controller that controls the newly created layer * * @throws IllegalArgumentException * If the parent(s) of the given configuration do not match the * configuration of the parent layers, including order * @throws LayerInstantiationException * If all modules cannot be defined to the same class loader for any * of the reasons listed above * @throws SecurityException * If `RuntimePermission("createClassLoader")` or * `RuntimePermission("getClassLoader")` is denied by * the security manager * * @see #findLoader */ static defineModulesWithOneLoader(cf: Configuration, parentLayers: ModuleLayer[], parentLoader: ClassLoader): Controller; /** * Creates a new module layer by defining the modules in the given ` * Configuration` to the Java virtual machine. Each module is defined to * its own {@link ClassLoader} created by this method. The {@link * ClassLoader#getParent() parent} of each class loader is the given parent * class loader. * * The class loaders created by this method implement direct * delegation when loading classes from modules. If the {@link * ClassLoader#loadClass(String, boolean) loadClass} method is invoked to * load a class then it uses the package name of the class to map it to a * module. The package may be in the module defined to the class loader. * The package may be exported by another module in this layer to the * module defined to the class loader. It may be in a package exported by a * module in a parent layer. The class loader delegates to the class loader * of the module, throwing `ClassNotFoundException` if not found by * that class loader. When `loadClass` is invoked to load a class * that does not map to a module then it delegates to the parent class * loader. * * The class loaders created by this method locate resources * ({@link ClassLoader#getResource(String) getResource}, {@link * ClassLoader#getResources(String) getResources}, and other resource * methods) in the module defined to the class loader before searching * the parent class loader. * * If there is a security manager then the class loaders created by * this method will load classes and resources with privileges that are * restricted by the calling context of this method. * * @param cf * The configuration for the layer * @param parentLayers * The list of parent layers in search order * @param parentLoader * The parent class loader for each of the class loaders created by * this method; may be `null` for the bootstrap class loader * * @return A controller that controls the newly created layer * * @throws IllegalArgumentException * If the parent(s) of the given configuration do not match the * configuration of the parent layers, including order * @throws LayerInstantiationException * If the layer cannot be created because the configuration contains * a module named "`java.base`" or a module contains a package * named "`java`" or a package with a name starting with * "`java.`" * * @throws SecurityException * If `RuntimePermission("createClassLoader")` or * `RuntimePermission("getClassLoader")` is denied by * the security manager * * @see #findLoader */ static defineModulesWithManyLoaders(cf: Configuration, parentLayers: ModuleLayer[], parentLoader: ClassLoader): Controller; /** * Creates a new module layer by defining the modules in the given ` * Configuration` to the Java virtual machine. The given function maps each * module in the configuration, by name, to a class loader. Creating the * layer informs the Java virtual machine about the classes that may be * loaded so that the Java virtual machine knows which module that each * class is a member of. * * The class loader delegation implemented by the class loaders must * respect module readability. The class loaders should be * {@link ClassLoader#registerAsParallelCapable parallel-capable} so as to * avoid deadlocks during class loading. In addition, the entity creating * a new layer with this method should arrange that the class loaders be * ready to load from these modules before there are any attempts to load * classes or resources. * * Creating a layer can fail for the following reasons: * * * * Two or more modules with the same package are mapped to the * same class loader. * * A module is mapped to a class loader that already has a * module of the same name defined to it. * * A module is mapped to a class loader that has already * defined types in any of the packages in the module. * * * * In addition, a layer cannot be created if the configuration contains * a module named "`java.base`", a configuration contains a module * with a package named "`java`" or a package name starting with * "`java.`", or the function to map a module name to a class loader * returns `null` or the {@linkplain ClassLoader#getPlatformClassLoader() * platform class loader}. * * If the function to map a module name to class loader throws an error * or runtime exception then it is propagated to the caller of this method. * * * @apiNote It is implementation specific as to whether creating a layer * with this method is an atomic operation or not. Consequentially it is * possible for this method to fail with some modules, but not all, defined * to the Java virtual machine. * * @param cf * The configuration for the layer * @param parentLayers * The list of parent layers in search order * @param clf * The function to map a module name to a class loader * * @return A controller that controls the newly created layer * * @throws IllegalArgumentException * If the parent(s) of the given configuration do not match the * configuration of the parent layers, including order * @throws LayerInstantiationException * If creating the layer fails for any of the reasons listed above * @throws SecurityException * If `RuntimePermission("getClassLoader")` is denied by * the security manager */ static defineModules(cf: Configuration, parentLayers: ModuleLayer[], clf: Function): Controller; /** * Returns the configuration for this layer. * * @return The configuration for this layer */ configuration(): Configuration; /** * Returns an unmodifiable list of this layer's parents, in search * order. If this is the {@linkplain #empty() empty layer} then an * empty list is returned. * * @return A possibly-empty unmodifiable list of this layer's parents */ parents(): ModuleLayer[]; /** * Returns an unmodifiable set of the modules in this layer. * * @return A possibly-empty unmodifiable set of the modules in this layer */ modules(): Set; /** * Returns the module with the given name in this layer, or if not in this * layer, the {@linkplain #parents() parent} layers. Finding a module in * parent layers is equivalent to invoking `findModule` on each * parent, in search order, until the module is found or all parents have * been searched. In a tree of layers then this is equivalent to * a depth-first search. * * @param name * The name of the module to find * * @return The module with the given name or an empty `Optional` * if there isn't a module with this name in this layer or any * parent layer */ findModule(name: string): Optional; /** * Returns the `ClassLoader` for the module with the given name. If * a module of the given name is not in this layer then the {@link #parents() * parent} layers are searched in the manner specified by {@link * #findModule(String) findModule}. * * If there is a security manager then its `checkPermission` * method is called with a `RuntimePermission("getClassLoader")` * permission to check that the caller is allowed to get access to the * class loader. * * @apiNote This method does not return an `Optional` * because `null` must be used to represent the bootstrap class loader. * * @param name * The name of the module to find * * @return The ClassLoader that the module is defined to * * @throws IllegalArgumentException if a module of the given name is not * defined in this layer or any parent of this layer * * @throws SecurityException if denied by the security manager */ findLoader(name: string): ClassLoader; /** * Returns a string describing this module layer. * * @return A possibly empty string describing this module layer */ toString(): string; /** * Returns the empty layer. There are no modules in the empty * layer. It has no parents. * * @return The empty layer */ static empty(): ModuleLayer; /** * Returns the boot layer. The boot layer contains at least one module, * `java.base`. Its parent is the {@link #empty() empty} layer. * * @apiNote This method returns `null` during startup and before * the boot layer is fully initialized. * * @return The boot layer */ static boot(): ModuleLayer; } /** * An informative annotation type used to indicate that an interface * type declaration is intended to be a functional interface as * defined by the Java Language Specification. * * Conceptually, a functional interface has exactly one abstract * method. Since {@linkplain java.lang.reflect.Method#isDefault() * default methods} have an implementation, they are not abstract. If * an interface declares an abstract method overriding one of the * public methods of `java.lang.Object`, that also does * not count toward the interface's abstract method count * since any implementation of the interface will have an * implementation from `java.lang.Object` or elsewhere. * * Note that instances of functional interfaces can be created with * lambda expressions, method references, or constructor references. * * If a type is annotated with this annotation type, compilers are * required to generate an error message unless: * * * The type is an interface type and not an annotation type, enum, or class. * The annotated type satisfies the requirements of a functional interface. * * * However, the compiler will treat any interface meeting the * definition of a functional interface as a functional interface * regardless of whether or not a `FunctionalInterface` * annotation is present on the interface declaration. * * @jls 4.3.2 The Class Object * @jls 9.8 Functional Interfaces * @jls 9.4.3 Interface Method Body * @jls 9.6.4.9 @FunctionalInterface * @since 1.8 */ export class FunctionalInterface { } /** * Thrown when an application tries to access an enum constant by name * and the enum type contains no constant with the specified name. * This exception can be thrown by the {@linkplain * java.lang.reflect.AnnotatedElement API used to read annotations * reflectively}. * * @author Josh Bloch * @see java.lang.reflect.AnnotatedElement * @since 1.5 */ export class EnumConstantNotPresentException extends RuntimeException { /** * Constructs an `EnumConstantNotPresentException` for the * specified constant. * * @param enumType the type of the missing enum constant * @param constantName the name of the missing enum constant */ constructor(enumType: Class, constantName: string); /** * Returns the type of the missing enum constant. * * @return the type of the missing enum constant */ enumType(): Class; /** * Returns the name of the missing enum constant. * * @return the name of the missing enum constant */ constantName(): string; } export class ProcessBuilder { /** * Constructs a process builder with the specified operating * system program and arguments. This constructor does not * make a copy of the `command` list. Subsequent * updates to the list will be reflected in the state of the * process builder. It is not checked whether * `command` corresponds to a valid operating system * command. * * @param command the list containing the program and its arguments */ constructor(command: string[]); /** * Constructs a process builder with the specified operating * system program and arguments. This is a convenience * constructor that sets the process builder's command to a string * list containing the same strings as the `command` * array, in the same order. It is not checked whether * `command` corresponds to a valid operating system * command. * * @param command a string array containing the program and its arguments */ constructor(...command: string[]); /** * Sets this process builder's operating system program and * arguments. This method does not make a copy of the * `command` list. Subsequent updates to the list will * be reflected in the state of the process builder. It is not * checked whether `command` corresponds to a valid * operating system command. * * @param command the list containing the program and its arguments * @return this process builder */ command(command: string[]): ProcessBuilder; /** * Sets this process builder's operating system program and * arguments. This is a convenience method that sets the command * to a string list containing the same strings as the * `command` array, in the same order. It is not * checked whether `command` corresponds to a valid * operating system command. * * @param command a string array containing the program and its arguments * @return this process builder */ command(...command: string[]): ProcessBuilder; /** * Returns this process builder's operating system program and * arguments. The returned list is not a copy. Subsequent * updates to the list will be reflected in the state of this * process builder. * * @return this process builder's program and its arguments */ command(): string[]; /** * Returns a string map view of this process builder's environment. * * Whenever a process builder is created, the environment is * initialized to a copy of the current process environment (see * {@link System#getenv()}). Subprocesses subsequently started by * this object's {@link #start()} method will use this map as * their environment. * * The returned object may be modified using ordinary {@link * java.util.Map Map} operations. These modifications will be * visible to subprocesses started via the {@link #start()} * method. Two `ProcessBuilder` instances always * contain independent process environments, so changes to the * returned map will never be reflected in any other * `ProcessBuilder` instance or the values returned by * {@link System#getenv System.getenv}. * * If the system does not support environment variables, an * empty map is returned. * * The returned map does not permit null keys or values. * Attempting to insert or query the presence of a null key or * value will throw a {@link NullPointerException}. * Attempting to query the presence of a key or value which is not * of type {@link String} will throw a {@link ClassCastException}. * * The behavior of the returned map is system-dependent. A * system may not allow modifications to environment variables or * may forbid certain variable names or values. For this reason, * attempts to modify the map may fail with * {@link UnsupportedOperationException} or * {@link IllegalArgumentException} * if the modification is not permitted by the operating system. * * Since the external format of environment variable names and * values is system-dependent, there may not be a one-to-one * mapping between them and Java's Unicode strings. Nevertheless, * the map is implemented in such a way that environment variables * which are not modified by Java code will have an unmodified * native representation in the subprocess. * * The returned map and its collection views may not obey the * general contract of the {@link Object#equals} and * {@link Object#hashCode} methods. * * The returned map is typically case-sensitive on all platforms. * * If a security manager exists, its * {@link SecurityManager#checkPermission checkPermission} method * is called with a * {@link RuntimePermission}`("getenv.*")` permission. * This may result in a {@link SecurityException} being thrown. * * When passing information to a Java subprocess, * system properties * are generally preferred over environment variables. * * @return this process builder's environment * * @throws SecurityException * if a security manager exists and its * {@link SecurityManager#checkPermission checkPermission} * method doesn't allow access to the process environment * * @see Runtime#exec(String[],String[],java.io.File) * @see System#getenv() */ environment(): Map; /** * Returns this process builder's working directory. * * Subprocesses subsequently started by this object's {@link * #start()} method will use this as their working directory. * The returned value may be `null` -- this means to use * the working directory of the current Java process, usually the * directory named by the system property `user.dir`, * as the working directory of the child process. * * @return this process builder's working directory */ directory(): File; /** * Sets this process builder's working directory. * * Subprocesses subsequently started by this object's {@link * #start()} method will use this as their working directory. * The argument may be `null` -- this means to use the * working directory of the current Java process, usually the * directory named by the system property `user.dir`, * as the working directory of the child process. * * @param directory the new working directory * @return this process builder */ directory(directory: File): ProcessBuilder; /** * Sets this process builder's standard input source. * * Subprocesses subsequently started by this object's {@link #start()} * method obtain their standard input from this source. * * If the source is {@link Redirect#PIPE Redirect.PIPE} * (the initial value), then the standard input of a * subprocess can be written to using the output stream * returned by {@link Process#getOutputStream()}. * If the source is set to any other value, then * {@link Process#getOutputStream()} will return a * null output stream. * * @param source the new standard input source * @return this process builder * @throws IllegalArgumentException * if the redirect does not correspond to a valid source * of data, that is, has type * {@link Redirect.Type#WRITE WRITE} or * {@link Redirect.Type#APPEND APPEND} * @since 1.7 */ redirectInput(source: Redirect): ProcessBuilder; /** * Sets this process builder's standard output destination. * * Subprocesses subsequently started by this object's {@link #start()} * method send their standard output to this destination. * * If the destination is {@link Redirect#PIPE Redirect.PIPE} * (the initial value), then the standard output of a subprocess * can be read using the input stream returned by {@link * Process#getInputStream()}. * If the destination is set to any other value, then * {@link Process#getInputStream()} will return a * null input stream. * * @param destination the new standard output destination * @return this process builder * @throws IllegalArgumentException * if the redirect does not correspond to a valid * destination of data, that is, has type * {@link Redirect.Type#READ READ} * @since 1.7 */ redirectOutput(destination: Redirect): ProcessBuilder; /** * Sets this process builder's standard error destination. * * Subprocesses subsequently started by this object's {@link #start()} * method send their standard error to this destination. * * If the destination is {@link Redirect#PIPE Redirect.PIPE} * (the initial value), then the error output of a subprocess * can be read using the input stream returned by {@link * Process#getErrorStream()}. * If the destination is set to any other value, then * {@link Process#getErrorStream()} will return a * null input stream. * * If the {@link #redirectErrorStream() redirectErrorStream} * attribute has been set `true`, then the redirection set * by this method has no effect. * * @param destination the new standard error destination * @return this process builder * @throws IllegalArgumentException * if the redirect does not correspond to a valid * destination of data, that is, has type * {@link Redirect.Type#READ READ} * @since 1.7 */ redirectError(destination: Redirect): ProcessBuilder; /** * Sets this process builder's standard input source to a file. * * This is a convenience method. An invocation of the form * `redirectInput(file)` * behaves in exactly the same way as the invocation * {@link #redirectInput(Redirect) redirectInput} * `(Redirect.from(file))`. * * @param file the new standard input source * @return this process builder * @since 1.7 */ redirectInput(file: File): ProcessBuilder; /** * Sets this process builder's standard output destination to a file. * * This is a convenience method. An invocation of the form * `redirectOutput(file)` * behaves in exactly the same way as the invocation * {@link #redirectOutput(Redirect) redirectOutput} * `(Redirect.to(file))`. * * @param file the new standard output destination * @return this process builder * @since 1.7 */ redirectOutput(file: File): ProcessBuilder; /** * Sets this process builder's standard error destination to a file. * * This is a convenience method. An invocation of the form * `redirectError(file)` * behaves in exactly the same way as the invocation * {@link #redirectError(Redirect) redirectError} * `(Redirect.to(file))`. * * @param file the new standard error destination * @return this process builder * @since 1.7 */ redirectError(file: File): ProcessBuilder; /** * Returns this process builder's standard input source. * * Subprocesses subsequently started by this object's {@link #start()} * method obtain their standard input from this source. * The initial value is {@link Redirect#PIPE Redirect.PIPE}. * * @return this process builder's standard input source * @since 1.7 */ redirectInput(): Redirect; /** * Returns this process builder's standard output destination. * * Subprocesses subsequently started by this object's {@link #start()} * method redirect their standard output to this destination. * The initial value is {@link Redirect#PIPE Redirect.PIPE}. * * @return this process builder's standard output destination * @since 1.7 */ redirectOutput(): Redirect; /** * Returns this process builder's standard error destination. * * Subprocesses subsequently started by this object's {@link #start()} * method redirect their standard error to this destination. * The initial value is {@link Redirect#PIPE Redirect.PIPE}. * * @return this process builder's standard error destination * @since 1.7 */ redirectError(): Redirect; /** * Sets the source and destination for subprocess standard I/O * to be the same as those of the current Java process. * * This is a convenience method. An invocation of the form * {@code * pb.inheritIO() * } * behaves in exactly the same way as the invocation * {@code * pb.redirectInput(Redirect.INHERIT) * .redirectOutput(Redirect.INHERIT) * .redirectError(Redirect.INHERIT) * } * * This gives behavior equivalent to most operating system * command interpreters, or the standard C library function * `system()`. * * @return this process builder * @since 1.7 */ inheritIO(): ProcessBuilder; /** * Tells whether this process builder merges standard error and * standard output. * * If this property is `true`, then any error output * generated by subprocesses subsequently started by this object's * {@link #start()} method will be merged with the standard * output, so that both can be read using the * {@link Process#getInputStream()} method. This makes it easier * to correlate error messages with the corresponding output. * The initial value is `false`. * * @return this process builder's `redirectErrorStream` property */ redirectErrorStream(): boolean; /** * Sets this process builder's `redirectErrorStream` property. * * If this property is `true`, then any error output * generated by subprocesses subsequently started by this object's * {@link #start()} method will be merged with the standard * output, so that both can be read using the * {@link Process#getInputStream()} method. This makes it easier * to correlate error messages with the corresponding output. * The initial value is `false`. * * @param redirectErrorStream the new property value * @return this process builder */ redirectErrorStream(redirectErrorStream: boolean): ProcessBuilder; /** * Starts a new process using the attributes of this process builder. * * The new process will * invoke the command and arguments given by {@link #command()}, * in a working directory as given by {@link #directory()}, * with a process environment as given by {@link #environment()}. * * This method checks that the command is a valid operating * system command. Which commands are valid is system-dependent, * but at the very least the command must be a non-empty list of * non-null strings. * * A minimal set of system dependent environment variables may * be required to start a process on some operating systems. * As a result, the subprocess may inherit additional environment variable * settings beyond those in the process builder's {@link #environment()}. * * If there is a security manager, its * {@link SecurityManager#checkExec checkExec} * method is called with the first component of this object's * `command` array as its argument. This may result in * a {@link SecurityException} being thrown. * * Starting an operating system process is highly system-dependent. * Among the many things that can go wrong are: * * The operating system program file was not found. * Access to the program file was denied. * The working directory does not exist. * Invalid character in command argument, such as NUL. * * * In such cases an exception will be thrown. The exact nature * of the exception is system-dependent, but it will always be a * subclass of {@link IOException}. * * If the operating system does not support the creation of * processes, an {@link UnsupportedOperationException} will be thrown. * * Subsequent modifications to this process builder will not * affect the returned {@link Process}. * * @return a new {@link Process} object for managing the subprocess * * @throws NullPointerException * if an element of the command list is null * * @throws IndexOutOfBoundsException * if the command is an empty list (has size `0`) * * @throws SecurityException * if a security manager exists and * * * its * {@link SecurityManager#checkExec checkExec} * method doesn't allow creation of the subprocess, or * * the standard input to the subprocess was * {@linkplain #redirectInput redirected from a file} * and the security manager's * {@link SecurityManager#checkRead(String) checkRead} method * denies read access to the file, or * * the standard output or standard error of the * subprocess was * {@linkplain #redirectOutput redirected to a file} * and the security manager's * {@link SecurityManager#checkWrite(String) checkWrite} method * denies write access to the file * * * * @throws UnsupportedOperationException * If the operating system does not support the creation of processes. * * @throws IOException if an I/O error occurs * * @see Runtime#exec(String[], String[], java.io.File) */ start(): Process; /** * Starts a Process for each ProcessBuilder, creating a pipeline of * processes linked by their standard output and standard input streams. * The attributes of each ProcessBuilder are used to start the respective * process except that as each process is started, its standard output * is directed to the standard input of the next. The redirects for standard * input of the first process and standard output of the last process are * initialized using the redirect settings of the respective ProcessBuilder. * All other `ProcessBuilder` redirects should be * {@link Redirect#PIPE Redirect.PIPE}. * * All input and output streams between the intermediate processes are * not accessible. * The {@link Process#getOutputStream standard input} of all processes * except the first process are null output streams * The {@link Process#getInputStream standard output} of all processes * except the last process are null input streams. * * The {@link #redirectErrorStream()} of each ProcessBuilder applies to the * respective process. If set to `true`, the error stream is written * to the same stream as standard output. * * If starting any of the processes throws an Exception, all processes * are forcibly destroyed. * * The `startPipeline` method performs the same checks on * each ProcessBuilder as does the {@link #start} method. Each new process * invokes the command and arguments given by the respective process builder's * {@link #command()}, in a working directory as given by its {@link #directory()}, * with a process environment as given by its {@link #environment()}. * * Each process builder's command is checked to be a valid operating * system command. Which commands are valid is system-dependent, * but at the very least the command must be a non-empty list of * non-null strings. * * A minimal set of system dependent environment variables may * be required to start a process on some operating systems. * As a result, the subprocess may inherit additional environment variable * settings beyond those in the process builder's {@link #environment()}. * * If there is a security manager, its * {@link SecurityManager#checkExec checkExec} * method is called with the first component of each process builder's * `command` array as its argument. This may result in * a {@link SecurityException} being thrown. * * Starting an operating system process is highly system-dependent. * Among the many things that can go wrong are: * * The operating system program file was not found. * Access to the program file was denied. * The working directory does not exist. * Invalid character in command argument, such as NUL. * * * In such cases an exception will be thrown. The exact nature * of the exception is system-dependent, but it will always be a * subclass of {@link IOException}. * * If the operating system does not support the creation of * processes, an {@link UnsupportedOperationException} will be thrown. * * Subsequent modifications to any of the specified builders * will not affect the returned {@link Process}. * @apiNote * For example to count the unique imports for all the files in a file hierarchy * on a Unix compatible platform: * {@code * String directory = "/home/duke/src"; * ProcessBuilder[] builders = { * new ProcessBuilder("find", directory, "-type", "f"), * new ProcessBuilder("xargs", "grep", "-h", "^import "), * new ProcessBuilder("awk", "{print $2;}"), * new ProcessBuilder("sort", "-u")}; * List processes = ProcessBuilder.startPipeline( * Arrays.asList(builders)); * Process last = processes.get(processes.size()-1); * try (InputStream is = last.getInputStream(); * Reader isr = new InputStreamReader(is); * BufferedReader r = new BufferedReader(isr)) { * long count = r.lines().count(); * } * } * * @param builders a List of ProcessBuilders * @return a `List`es started from the corresponding * ProcessBuilder * @throws IllegalArgumentException any of the redirects except the * standard input of the first builder and the standard output of * the last builder are not {@link Redirect#PIPE}. * @throws NullPointerException * if an element of the command list is null or * if an element of the ProcessBuilder list is null or * the builders argument is null * @throws IndexOutOfBoundsException * if the command is an empty list (has size `0`) * @throws SecurityException * if a security manager exists and * * its * {@link SecurityManager#checkExec checkExec} * method doesn't allow creation of the subprocess, or * the standard input to the subprocess was * {@linkplain #redirectInput redirected from a file} * and the security manager's * {@link SecurityManager#checkRead(String) checkRead} method * denies read access to the file, or * the standard output or standard error of the * subprocess was * {@linkplain #redirectOutput redirected to a file} * and the security manager's * {@link SecurityManager#checkWrite(String) checkWrite} method * denies write access to the file * * * @throws UnsupportedOperationException * If the operating system does not support the creation of processes * * @throws IOException if an I/O error occurs * @since 9 */ static startPipeline(builders: ProcessBuilder[]): Process[]; } /** * Represents metadata about a run-time package associated with a class loader. * Metadata includes annotations, versioning, and sealing. * * Annotations for the run-time package are read from `package-info.class` * at the same code source as classes in the run-time package. * * The set of classes that make up the run-time package may implement a * particular specification. The specification title, version, and vendor * (indicating the owner/maintainer of the specification) can be provided * when the `Package` is defined. An application can ask if the * `Package` is compatible with a particular specification version * by using the {@link #isCompatibleWith Package.isCompatibleWith(String)} * method. In addition, information about the actual classes that make up the * run-time package can be provided when the `Package` is defined. * This information consists of an implementation title, version, and vendor * (indicating the supplier of the classes). * * A `Package` may be explicitly defined with * the {@link ClassLoader#definePackage(String, String, String, String, * String, String, String, URL)} method. * The caller supplies the specification and implementation titles, versions, and * vendors. The caller also indicates whether the package is * {@linkplain java.util.jar.Attributes.Name#SEALED sealed}. * If a `Package` is not explicitly defined for a run-time package when * a class in that run-time package is defined, then a `Package` is * automatically defined by the class's defining class loader, as follows. * * A `Package` automatically defined for classes in a named module has * the following properties: * * The name of the package is derived from the {@linkplain Class#getName() binary names} * of the classes. Since classes in a named module must be in a named package, * the derived name is never empty. * The package is sealed with the {@linkplain java.lang.module.ModuleReference#location() * module location} as the code source, if known. * The specification and implementation titles, versions, and vendors * are unspecified. * Any annotations on the package are read from `package-info.class` * as specified above. * * * A `Package` automatically defined for classes in an unnamed module * has the following properties: * * The name of the package is either `""` (for classes in an unnamed package) * or derived from the {@linkplain Class#getName() binary names} of the classes * (for classes in a named package). * The package is not sealed. * The specification and implementation titles, versions, and vendors * are unspecified. * Any annotations on the package are read from `package-info.class` * as specified above. * * * * A `Package` can be obtained with the {@link Package#getPackage * Package.getPackage(String)} and {@link ClassLoader#getDefinedPackage * ClassLoader.getDefinedPackage(String)} methods. * Every `Package` defined by a class loader can be obtained * with the {@link Package#getPackages Package.getPackages()} and * {@link ClassLoader#getDefinedPackages} methods. * * @implNote * The builtin class loaders * do not explicitly define `Package` objects for packages in * named modules. Instead those packages are automatically defined * and have no specification and implementation versioning information. * * @jvms 5.3 Creation and Loading * @see * The JAR File Specification: Package Sealing * @see ClassLoader#definePackage(String, String, String, String, String, String, String, URL) * * @since 1.2 * @revised 9 */ export class Package extends AnnotatedElement { /** * Return the name of this package. * * @return The fully-qualified name of this package as defined in section {@jls 6.5.3} of * The Java Language Specification, * for example, `java.lang` */ get name(): string; /** * Return the title of the specification that this package implements. * @return the specification title, `null` is returned if it is not known. */ get specificationTitle(): string; /** * Returns the version number of the specification * that this package implements. * This version string must be a sequence of non-negative decimal * integers separated by "."'s and may have leading zeros. * When version strings are compared the most significant * numbers are compared. * * * Specification version numbers use a syntax that consists of non-negative * decimal integers separated by periods ".", for example "2.0" or * "1.2.3.4.5.6.7". This allows an extensible number to be used to represent * major, minor, micro, etc. versions. The version specification is described * by the following formal grammar: * * * SpecificationVersion: * Digits RefinedVersionopt * * RefinedVersion: * `.` Digits * `.` Digits RefinedVersion * * Digits: * Digit * Digits * * Digit: * any character for which {@link Character#isDigit} returns `true`, * e.g. 0, 1, 2, ... * * * * @return the specification version, `null` is returned if it is not known. */ get specificationVersion(): string; /** * Return the name of the organization, vendor, * or company that owns and maintains the specification * of the classes that implement this package. * @return the specification vendor, `null` is returned if it is not known. */ get specificationVendor(): string; /** * Return the title of this package. * @return the title of the implementation, `null` is returned if it is not known. */ get implementationTitle(): string; /** * Return the version of this implementation. It consists of any string * assigned by the vendor of this implementation and does * not have any particular syntax specified or expected by the Java * runtime. It may be compared for equality with other * package version strings used for this implementation * by this vendor for this package. * @return the version of the implementation, `null` is returned if it is not known. */ get implementationVersion(): string; /** * Returns the vendor that implemented this package, `null` * is returned if it is not known. * @return the vendor that implemented this package, `null` * is returned if it is not known. * * @revised 9 */ get implementationVendor(): string; /** * Returns true if this package is sealed. * * @apiNote * Package sealing * has no relationship with {@linkplain Class#isSealed() sealed classes or interfaces}. * Package sealing is specific to JAR files defined for classes in an unnamed module. * See the {@link Package Package} class specification for details * how a `Package` is defined as sealed package. * * @return true if the package is sealed, false otherwise * */ isSealed(): boolean; /** * Returns true if this package is sealed with respect to the specified * code source `url`. * * @apiNote * Package sealing * has no relationship with {@linkplain Class#isSealed() sealed classes or interfaces}. * Package sealing is specific to JAR files defined for classes in an unnamed module. * See the {@link Package Package} class specification for details * how a `Package` is defined as sealed package. * * @param url the code source URL * @return true if this package is sealed with respect to the given `url` */ isSealed(url: URL): boolean; /** * Compare this package's specification version with a * desired version. It returns true if * this packages specification version number is greater than or equal * to the desired version number. * * Version numbers are compared by sequentially comparing corresponding * components of the desired and specification strings. * Each component is converted as a decimal integer and the values * compared. * If the specification value is greater than the desired * value true is returned. If the value is less false is returned. * If the values are equal the period is skipped and the next pair of * components is compared. * * @param desired the version string of the desired version. * @return true if this package's version number is greater * than or equal to the desired version number * * @throws NumberFormatException if the current version is not known or * the desired or current version is not of the correct dotted form. */ isCompatibleWith(desired: string): boolean; /** * Finds a package by name in the caller's class loader and its * ancestors. * * If the caller's class loader defines a `Package` of the given name, * the `Package` is returned. Otherwise, the ancestors of the * caller's class loader are searched recursively (parent by parent) * for a `Package` of the given name. * * Calling this method is equivalent to calling {@link ClassLoader#getPackage} * on a `ClassLoader` instance which is the caller's class loader. * * @param name A package name, such as "`java.lang`". * @return The `Package` of the given name defined by the caller's * class loader or its ancestors, or `null` if not found. * * @throws NullPointerException * if `name` is `null`. * * @deprecated * If multiple class loaders delegate to each other and define classes * with the same package name, and one such loader relies on the lookup * behavior of `getPackage` to return a `Package` from * a parent loader, then the properties exposed by the `Package` * may not be as expected in the rest of the program. * For example, the `Package` will only expose annotations from the * `package-info.class` file defined by the parent loader, even if * annotations exist in a `package-info.class` file defined by * a child loader. A more robust approach is to use the * {@link ClassLoader#getDefinedPackage} method which returns * a `Package` for the specified class loader. * * @see ClassLoader#getDefinedPackage * * @revised 9 */ static getPackage(name: string): Package; /** * Returns all of the `Package`s defined by the caller's class loader * and its ancestors. The returned array may contain more than one * `Package` object of the same package name, each defined by * a different class loader in the class loader hierarchy. * * Calling this method is equivalent to calling {@link ClassLoader#getPackages} * on a `ClassLoader` instance which is the caller's class loader. * * @return The array of `Package` objects defined by this * class loader and its ancestors * * @see ClassLoader#getDefinedPackages * * @revised 9 */ static get packages(): Package[]; /** * Return the hash code computed from the package name. * @return the hash code computed from the package name. */ hashCode(): number; /** * Returns the string representation of this Package. * Its value is the string "package " and the package name. * If the package title is defined it is appended. * If the package version is defined it is appended. * @return the string representation of the package. */ toString(): string; /** * {@inheritDoc} * Note that any annotation returned by this method is a * declaration annotation. * * @throws NullPointerException {@inheritDoc} * @since 1.5 */ getAnnotation(annotationClass: Class): A; /** * {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @since 1.5 */ isAnnotationPresent(annotationClass: Class): boolean; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. * * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getAnnotationsByType(annotationClass: Class): A[]; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. * @since 1.5 */ get annotations(): Annotation[]; /** * {@inheritDoc} * Note that any annotation returned by this method is a * declaration annotation. * * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getDeclaredAnnotation(annotationClass: Class): A; /** * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getDeclaredAnnotationsByType(annotationClass: Class): A[]; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. * @since 1.5 */ get declaredAnnotations(): Annotation[]; } /** * Instances of the class `Class` represent classes and * interfaces in a running Java application. An enum class and a record * class are kinds of class; an annotation interface is a kind of * interface. Every array also belongs to a class that is reflected as * a `Class` object that is shared by all arrays with the same * element type and number of dimensions. The primitive Java types * (`boolean`, `byte`, `char`, `short`, ` * int`, `long`, `float`, and `double`), and the * keyword `void` are also represented as `Class` objects. * * `Class` has no public constructor. Instead a `Class` * object is constructed automatically by the Java Virtual Machine when * a class is derived from the bytes of a `class` file through * the invocation of one of the following methods: * * {@link ClassLoader#defineClass(String, byte[], int, int) ClassLoader::defineClass} * {@link java.lang.invoke.MethodHandles.Lookup#defineClass(byte[]) * java.lang.invoke.MethodHandles.Lookup::defineClass} * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...) * java.lang.invoke.MethodHandles.Lookup::defineHiddenClass} * * * The methods of class `Class` expose many characteristics of a * class or interface. Most characteristics are derived from the `class` * file that the class loader passed to the Java Virtual Machine or * from the `class` file passed to `Lookup::defineClass` * or `Lookup::defineHiddenClass`. * A few characteristics are determined by the class loading environment * at run time, such as the module returned by {@link #getModule() getModule()}. * * The following example uses a `Class` object to print the * class name of an object: * * * void printClassName(Object obj) { * System.out.println("The class of " + obj + * " is " + obj.getClass().getName()); * } * * * It is also possible to get the `Class` object for a named * class or interface (or for `void`) using a class literal. * For example: * * * `System.out.println("The name of class Foo is: "+Foo.class.getName());` * * * Some methods of class `Class` expose whether the declaration of * a class or interface in Java source code was enclosed within * another declaration. Other methods describe how a class or interface * is situated in a nest. A nest is a set of * classes and interfaces, in the same run-time package, that * allow mutual access to their `private` members. * The classes and interfaces are known as nestmates. * One nestmate acts as the * nest host, and enumerates the other nestmates which * belong to the nest; each of them in turn records it as the nest host. * The classes and interfaces which belong to a nest, including its host, are * determined when * `class` files are generated, for example, a Java compiler * will typically record a top-level class as the host of a nest where the * other members are the classes and interfaces whose declarations are * enclosed within the top-level class declaration. * * A class or interface created by the invocation of * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...) * Lookup::defineHiddenClass} is a {@linkplain Class#isHidden() hidden} * class or interface. * All kinds of class, including enum classes and record classes, may be * hidden classes; all kinds of interface, including annotation interfaces, * may be hidden interfaces. * * The {@linkplain #getName() name of a hidden class or interface} is * not a binary name, * which means the following: * * A hidden class or interface cannot be referenced by the constant pools * of other classes and interfaces. * A hidden class or interface cannot be described in * {@linkplain java.lang.constant.ConstantDesc nominal form} by * {@link #describeConstable() Class::describeConstable}, * {@link ClassDesc#of(String) ClassDesc::of}, or * {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}. * A hidden class or interface cannot be discovered by {@link #forName Class::forName} * or {@link ClassLoader#loadClass(String, boolean) ClassLoader::loadClass}. * * * A hidden class or interface is never an array class, but may be * the element type of an array. In all other respects, the fact that * a class or interface is hidden has no bearing on the characteristics * exposed by the methods of class `Class`. * * @param the type of the class modeled by this `Class` * object. For example, the type of `String.class` is ` * Class`. Use `Class` if the class being modeled is * unknown. * * @see java.lang.ClassLoader#defineClass(byte[], int, int) * @since 1.0 * @jls 15.8.2 Class Literals */ export class Class extends Serializable { /** * Converts the object to a string. The string representation is the * string "class" or "interface", followed by a space, and then by the * name of the class in the format returned by `getName`. * If this `Class` object represents a primitive type, * this method returns the name of the primitive type. If * this `Class` object represents void this method returns * "void". If this `Class` object represents an array type, * this method returns "class " followed by `getName`. * * @return a string representation of this `Class` object. */ toString(): string; /** * Returns a string describing this `Class`, including * information about modifiers and type parameters. * * The string is formatted as a list of type modifiers, if any, * followed by the kind of type (empty string for primitive types * and `class`, `enum`, `interface`, * `@interface`, or `record` as appropriate), followed * by the type's name, followed by an angle-bracketed * comma-separated list of the type's type parameters, if any, * including informative bounds on the type parameters, if any. * * A space is used to separate modifiers from one another and to * separate any modifiers from the kind of type. The modifiers * occur in canonical order. If there are no type parameters, the * type parameter list is elided. * * For an array type, the string starts with the type name, * followed by an angle-bracketed comma-separated list of the * type's type parameters, if any, followed by a sequence of * `[]` characters, one set of brackets per dimension of * the array. * * Note that since information about the runtime representation * of a type is being generated, modifiers not present on the * originating source code or illegal on the originating source * code may be present. * * @return a string describing this `Class`, including * information about modifiers and type parameters * * @since 1.8 */ toGenericString(): string; /** * Returns the `Class` object associated with the class or * interface with the given string name. Invoking this method is * equivalent to: * * * `Class.forName(className, true, currentLoader)` * * * where `currentLoader` denotes the defining class loader of * the current class. * * For example, the following code fragment returns the * runtime `Class` descriptor for the class named * `java.lang.Thread`: * * * `Class t = Class.forName("java.lang.Thread")` * * * A call to `forName("X")` causes the class named * `X` to be initialized. * * @param className the fully qualified name of the desired class. * @return the `Class` object for the class with the * specified name. * @throws LinkageError if the linkage fails * @throws ExceptionInInitializerError if the initialization provoked * by this method fails * @throws ClassNotFoundException if the class cannot be located * * @jls 12.2 Loading of Classes and Interfaces * @jls 12.3 Linking of Classes and Interfaces * @jls 12.4 Initialization of Classes and Interfaces */ static forName(className: string): Class; /** * Returns the `Class` object associated with the class or * interface with the given string name, using the given class loader. * Given the fully qualified name for a class or interface (in the same * format returned by `getName`) this method attempts to * locate and load the class or interface. The specified class * loader is used to load the class or interface. If the parameter * `loader` is null, the class is loaded through the bootstrap * class loader. The class is initialized only if the * `initialize` parameter is `true` and if it has * not been initialized earlier. * * If `name` denotes a primitive type or void, an attempt * will be made to locate a user-defined class in the unnamed package whose * name is `name`. Therefore, this method cannot be used to * obtain any of the `Class` objects representing primitive * types or void. * * If `name` denotes an array class, the component type of * the array class is loaded but not initialized. * * For example, in an instance method the expression: * * * `Class.forName("Foo")` * * * is equivalent to: * * * `Class.forName("Foo", true, this.getClass().getClassLoader())` * * * Note that this method throws errors related to loading, linking * or initializing as specified in Sections {@jls 12.2}, {@jls * 12.3}, and {@jls 12.4} of The Java Language * Specification. * Note that this method does not check whether the requested class * is accessible to its caller. * * @param name fully qualified name of the desired class * @param initialize if `true` the class will be initialized * (which implies linking). See Section {@jls * 12.4} of The Java Language * Specification. * @param loader class loader from which the class must be loaded * @return class object representing the desired class * * @throws LinkageError if the linkage fails * @throws ExceptionInInitializerError if the initialization provoked * by this method fails * @throws ClassNotFoundException if the class cannot be located by * the specified class loader * @throws SecurityException * if a security manager is present, and the `loader` is * `null`, and the caller's class loader is not * `null`, and the caller does not have the * {@link RuntimePermission}`("getClassLoader")` * * @see java.lang.Class#forName(String) * @see java.lang.ClassLoader * * @jls 12.2 Loading of Classes and Interfaces * @jls 12.3 Linking of Classes and Interfaces * @jls 12.4 Initialization of Classes and Interfaces * @since 1.2 */ static forName(name: string, initialize: boolean, loader: ClassLoader): Class; /** * Returns the `Class` with the given * binary name in the given module. * * This method attempts to locate and load the class or interface. * It does not link the class, and does not run the class initializer. * If the class is not found, this method returns `null`. * * If the class loader of the given module defines other modules and * the given name is a class defined in a different module, this method * returns `null` after the class is loaded. * * This method does not check whether the requested class is * accessible to its caller. * * @apiNote * This method returns `null` on failure rather than * throwing a {@link ClassNotFoundException}, as is done by * the {@link #forName(String, boolean, ClassLoader)} method. * The security check is a stack-based permission check if the caller * loads a class in another module. * * @param module A module * @param name The binary name * of the class * @return `Class` object of the given name defined in the given module; * `null` if not found. * * @throws NullPointerException if the given module or name is `null` * * @throws LinkageError if the linkage fails * * @throws SecurityException * * if the caller is not the specified module and * `RuntimePermission("getClassLoader")` permission is denied; or * access to the module content is denied. For example, * permission check will be performed when a class loader calls * {@link ModuleReader#open(String)} to read the bytes of a class file * in a module. * * * @jls 12.2 Loading of Classes and Interfaces * @jls 12.3 Linking of Classes and Interfaces * @since 9 */ static forName(module: Module, name: string): Class; /** * Creates a new instance of the class represented by this `Class` * object. The class is instantiated as if by a `new` * expression with an empty argument list. The class is initialized if it * has not already been initialized. * * @deprecated This method propagates any exception thrown by the * nullary constructor, including a checked exception. Use of * this method effectively bypasses the compile-time exception * checking that would otherwise be performed by the compiler. * The {@link * java.lang.reflect.Constructor#newInstance(java.lang.Object...) * Constructor.newInstance} method avoids this problem by wrapping * any exception thrown by the constructor in a (checked) {@link * java.lang.reflect.InvocationTargetException}. * * The call * * {@code * clazz.newInstance() * } * * can be replaced by * * {@code * clazz.getDeclaredConstructor().newInstance() * } * * The latter sequence of calls is inferred to be able to throw * the additional exception types {@link * InvocationTargetException} and {@link * NoSuchMethodException}. Both of these exception types are * subclasses of {@link ReflectiveOperationException}. * * @return a newly allocated instance of the class represented by this * object. * @throws IllegalAccessException if the class or its nullary * constructor is not accessible. * @throws InstantiationException * if this `Class` represents an abstract class, * an interface, an array class, a primitive type, or void; * or if the class has no nullary constructor; * or if the instantiation fails for some other reason. * @throws ExceptionInInitializerError if the initialization * provoked by this method fails. * @throws SecurityException * If a security manager, s, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class. */ newInstance(): T; /** * Determines if the specified `Object` is assignment-compatible * with the object represented by this `Class`. This method is * the dynamic equivalent of the Java language `instanceof` * operator. The method returns `true` if the specified * `Object` argument is non-null and can be cast to the * reference type represented by this `Class` object without * raising a `ClassCastException.` It returns `false` * otherwise. * * Specifically, if this `Class` object represents a * declared class, this method returns `true` if the specified * `Object` argument is an instance of the represented class (or * of any of its subclasses); it returns `false` otherwise. If * this `Class` object represents an array class, this method * returns `true` if the specified `Object` argument * can be converted to an object of the array class by an identity * conversion or by a widening reference conversion; it returns * `false` otherwise. If this `Class` object * represents an interface, this method returns `true` if the * class or any superclass of the specified `Object` argument * implements this interface; it returns `false` otherwise. If * this `Class` object represents a primitive type, this method * returns `false`. * * @param obj the object to check * @return true if `obj` is an instance of this class * * @since 1.1 */ isInstance(obj: any): boolean; /** * Determines if the class or interface represented by this * `Class` object is either the same as, or is a superclass or * superinterface of, the class or interface represented by the specified * `Class` parameter. It returns `true` if so; * otherwise it returns `false`. If this `Class` * object represents a primitive type, this method returns * `true` if the specified `Class` parameter is * exactly this `Class` object; otherwise it returns * `false`. * * Specifically, this method tests whether the type represented by the * specified `Class` parameter can be converted to the type * represented by this `Class` object via an identity conversion * or via a widening reference conversion. See The Java Language * Specification, sections {@jls 5.1.1} and {@jls 5.1.4}, * for details. * * @param cls the `Class` object to be checked * @return the `boolean` value indicating whether objects of the * type `cls` can be assigned to objects of this class * @throws NullPointerException if the specified Class parameter is * null. * @since 1.1 */ isAssignableFrom(cls: Class): boolean; /** * Determines if this `Class` object represents an * interface type. * * @return `true` if this `Class` object represents an interface; * `false` otherwise. */ isInterface(): boolean; /** * Determines if this `Class` object represents an array class. * * @return `true` if this `Class` object represents an array class; * `false` otherwise. * @since 1.1 */ isArray(): boolean; /** * Determines if the specified `Class` object represents a * primitive type. * * There are nine predefined `Class` objects to represent * the eight primitive types and void. These are created by the Java * Virtual Machine, and have the same names as the primitive types that * they represent, namely `boolean`, `byte`, * `char`, `short`, `int`, * `long`, `float`, and `double`. * * These objects may only be accessed via the following public static * final variables, and are the only `Class` objects for which * this method returns `true`. * * @return true if and only if this class represents a primitive type * * @see java.lang.Boolean#TYPE * @see java.lang.Character#TYPE * @see java.lang.Byte#TYPE * @see java.lang.Short#TYPE * @see java.lang.Integer#TYPE * @see java.lang.Long#TYPE * @see java.lang.Float#TYPE * @see java.lang.Double#TYPE * @see java.lang.Void#TYPE * @since 1.1 */ isPrimitive(): boolean; /** * Returns true if this `Class` object represents an annotation * interface. Note that if this method returns true, {@link #isInterface()} * would also return true, as all annotation interfaces are also interfaces. * * @return `true` if this `Class` object represents an annotation * interface; `false` otherwise * @since 1.5 */ isAnnotation(): boolean; /** * Returns `true` if and only if this class has the synthetic modifier * bit set. * * @return `true` if and only if this class has the synthetic modifier bit set * @jls 13.1 The Form of a Binary * @jvms 4.1 The `ClassFile` Structure * @since 1.5 */ isSynthetic(): boolean; /** * Returns the name of the entity (class, interface, array class, * primitive type, or void) represented by this `Class` object. * * If this `Class` object represents a class or interface, * not an array class, then: * * If the class or interface is not {@linkplain #isHidden() hidden}, * then the binary name * of the class or interface is returned. * If the class or interface is hidden, then the result is a string * of the form: `N + '/' + ` * where `N` is the binary name * indicated by the `class` file passed to * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...) * Lookup::defineHiddenClass}, and `` is an unqualified name. * * * If this `Class` object represents an array class, then * the result is a string consisting of one or more '`[`' characters * representing the depth of the array nesting, followed by the element * type as encoded using the following table: * * * Element types and encodings * * Element Type Encoding * * * `boolean` `Z` * `byte` `B` * `char` `C` * class or interface with binary name N * `L`N`;` * `double` `D` * `float` `F` * `int` `I` * `long` `J` * `short` `S` * * * * If this `Class` object represents a primitive type or `void`, * then the result is a string with the same spelling as the Java language * keyword which corresponds to the primitive type or `void`. * * Examples: * * String.class.getName() * returns "java.lang.String" * byte.class.getName() * returns "byte" * (new Object[3]).getClass().getName() * returns "[Ljava.lang.Object;" * (new int[3][4][5][6][7][8][9]).getClass().getName() * returns "[[[[[[[I" * * * @return the name of the class, interface, or other entity * represented by this `Class` object. * @jls 13.1 The Form of a Binary */ get name(): string; /** * Returns the class loader for the class. Some implementations may use * null to represent the bootstrap class loader. This method will return * null in such implementations if this class was loaded by the bootstrap * class loader. * * If this `Class` object * represents a primitive type or void, null is returned. * * @return the class loader that loaded the class or interface * represented by this `Class` object. * @throws SecurityException * if a security manager is present, and the caller's class loader * is not `null` and is not the same as or an ancestor of the * class loader for the class whose class loader is requested, * and the caller does not have the * {@link RuntimePermission}`("getClassLoader")` * @see java.lang.ClassLoader * @see SecurityManager#checkPermission * @see java.lang.RuntimePermission */ get classLoader(): ClassLoader; /** * Returns the module that this class or interface is a member of. * * If this class represents an array type then this method returns the * `Module` for the element type. If this class represents a * primitive type or void, then the `Module` object for the * `java.base` module is returned. * * If this class is in an unnamed module then the {@linkplain * ClassLoader#getUnnamedModule() unnamed} `Module` of the class * loader for this class is returned. * * @return the module that this class or interface is a member of * * @since 9 */ get module(): Module; /** * Returns an array of `TypeVariable` objects that represent the * type variables declared by the generic declaration represented by this * `GenericDeclaration` object, in declaration order. Returns an * array of length 0 if the underlying generic declaration declares no type * variables. * * @return an array of `TypeVariable` objects that represent * the type variables declared by this generic declaration * @throws java.lang.reflect.GenericSignatureFormatError if the generic * signature of this generic declaration does not conform to * the format specified in section {@jvms 4.7.9} of * The Java Virtual Machine Specification * @since 1.5 */ get typeParameters(): TypeVariable[]; /** * Returns the `Class` representing the direct superclass of the * entity (class, interface, primitive type or void) represented by * this `Class`. If this `Class` represents either the * `Object` class, an interface, a primitive type, or void, then * null is returned. If this `Class` object represents an array class * then the `Class` object representing the `Object` class is * returned. * * @return the direct superclass of the class represented by this `Class` object */ get superclass(): Class; /** * Returns the `Type` representing the direct superclass of * the entity (class, interface, primitive type or void) represented by * this `Class` object. * * If the superclass is a parameterized type, the `Type` * object returned must accurately reflect the actual type * arguments used in the source code. The parameterized type * representing the superclass is created if it had not been * created before. See the declaration of {@link * java.lang.reflect.ParameterizedType ParameterizedType} for the * semantics of the creation process for parameterized types. If * this `Class` object represents either the `Object` * class, an interface, a primitive type, or void, then null is * returned. If this `Class` object represents an array class * then the `Class` object representing the `Object` class is * returned. * * @throws java.lang.reflect.GenericSignatureFormatError if the generic * class signature does not conform to the format specified in * section {@jvms 4.7.9} of The Java Virtual * Machine Specification * @throws TypeNotPresentException if the generic superclass * refers to a non-existent type declaration * @throws java.lang.reflect.MalformedParameterizedTypeException if the * generic superclass refers to a parameterized type that cannot be * instantiated for any reason * @return the direct superclass of the class represented by this `Class` object * @since 1.5 */ get genericSuperclass(): Type; /** * Gets the package of this class. * * If this class represents an array type, a primitive type or void, * this method returns `null`. * * @return the package of this class. * @revised 9 */ get package(): Package; /** * Returns the fully qualified package name. * * If this class is a top level class, then this method returns the fully * qualified name of the package that the class is a member of, or the * empty string if the class is in an unnamed package. * * If this class is a member class, then this method is equivalent to * invoking `getPackageName()` on the {@linkplain #getEnclosingClass * enclosing class}. * * If this class is a {@linkplain #isLocalClass local class} or an {@linkplain * #isAnonymousClass() anonymous class}, then this method is equivalent to * invoking `getPackageName()` on the {@linkplain #getDeclaringClass * declaring class} of the {@linkplain #getEnclosingMethod enclosing method} or * {@linkplain #getEnclosingConstructor enclosing constructor}. * * If this class represents an array type then this method returns the * package name of the element type. If this class represents a primitive * type or void then the package name "`java.lang`" is returned. * * @return the fully qualified package name * * @since 9 * @jls 6.7 Fully Qualified Names */ get packageName(): string; /** * Returns the interfaces directly implemented by the class or interface * represented by this `Class` object. * * If this `Class` object represents a class, the return value is an array * containing objects representing all interfaces directly implemented by * the class. The order of the interface objects in the array corresponds * to the order of the interface names in the `implements` clause of * the declaration of the class represented by this `Class` object. For example, * given the declaration: * * `class Shimmer implements FloorWax, DessertTopping { ... `} * * suppose the value of `s` is an instance of * `Shimmer`; the value of the expression: * * `s.getClass().getInterfaces()[0]` * * is the `Class` object that represents interface * `FloorWax`; and the value of: * * `s.getClass().getInterfaces()[1]` * * is the `Class` object that represents interface * `DessertTopping`. * * If this `Class` object represents an interface, the array contains objects * representing all interfaces directly extended by the interface. The * order of the interface objects in the array corresponds to the order of * the interface names in the `extends` clause of the declaration of * the interface represented by this `Class` object. * * If this `Class` object represents a class or interface that implements no * interfaces, the method returns an array of length 0. * * If this `Class` object represents a primitive type or void, the method * returns an array of length 0. * * If this `Class` object represents an array type, the * interfaces `Cloneable` and `java.io.Serializable` are * returned in that order. * * @return an array of interfaces directly implemented by this class */ get interfaces(): Class[]; /** * Returns the `Type`s representing the interfaces * directly implemented by the class or interface represented by * this `Class` object. * * If a superinterface is a parameterized type, the * `Type` object returned for it must accurately reflect * the actual type arguments used in the source code. The * parameterized type representing each superinterface is created * if it had not been created before. See the declaration of * {@link java.lang.reflect.ParameterizedType ParameterizedType} * for the semantics of the creation process for parameterized * types. * * If this `Class` object represents a class, the return value is an array * containing objects representing all interfaces directly implemented by * the class. The order of the interface objects in the array corresponds * to the order of the interface names in the `implements` clause of * the declaration of the class represented by this `Class` object. * * If this `Class` object represents an interface, the array contains objects * representing all interfaces directly extended by the interface. The * order of the interface objects in the array corresponds to the order of * the interface names in the `extends` clause of the declaration of * the interface represented by this `Class` object. * * If this `Class` object represents a class or interface that implements no * interfaces, the method returns an array of length 0. * * If this `Class` object represents a primitive type or void, the method * returns an array of length 0. * * If this `Class` object represents an array type, the * interfaces `Cloneable` and `java.io.Serializable` are * returned in that order. * * @throws java.lang.reflect.GenericSignatureFormatError * if the generic class signature does not conform to the * format specified in section {@jvms 4.7.9} of The * Java Virtual Machine Specification * @throws TypeNotPresentException if any of the generic * superinterfaces refers to a non-existent type declaration * @throws java.lang.reflect.MalformedParameterizedTypeException * if any of the generic superinterfaces refer to a parameterized * type that cannot be instantiated for any reason * @return an array of interfaces directly implemented by this class * @since 1.5 */ get genericInterfaces(): Type[]; /** * Returns the `Class` representing the component type of an * array. If this class does not represent an array class this method * returns null. * * @return the `Class` representing the component type of this * class if this class is an array * @see java.lang.reflect.Array * @since 1.1 */ get componentType(): Class; /** * Returns the Java language modifiers for this class or interface, encoded * in an integer. The modifiers consist of the Java Virtual Machine's * constants for `public`, `protected`, * `private`, `final`, `static`, * `abstract` and `interface`; they should be decoded * using the methods of class `Modifier`. * * If the underlying class is an array class, then its * `public`, `private` and `protected` * modifiers are the same as those of its component type. If this * `Class` object represents a primitive type or void, its * `public` modifier is always `true`, and its * `protected` and `private` modifiers are always * `false`. If this `Class` object represents an array class, a * primitive type or void, then its `final` modifier is always * `true` and its interface modifier is always * `false`. The values of its other modifiers are not determined * by this specification. * * The modifier encodings are defined in section {@jvms 4.1} * of The Java Virtual Machine Specification. * * @return the `int` representing the modifiers for this class * @see java.lang.reflect.Modifier * @since 1.1 */ get modifiers(): number; /** * Gets the signers of this class. * * @return the signers of this class, or null if there are no signers. In * particular, this method returns null if this `Class` object represents * a primitive type or void. * @since 1.1 */ get signers(): any[]; /** * If this `Class` object represents a local or anonymous * class within a method, returns a {@link * java.lang.reflect.Method Method} object representing the * immediately enclosing method of the underlying class. Returns * `null` otherwise. * * In particular, this method returns `null` if the underlying * class is a local or anonymous class immediately enclosed by a class or * interface declaration, instance initializer or static initializer. * * @return the immediately enclosing method of the underlying class, if * that class is a local or anonymous class; otherwise `null`. * * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of the enclosing class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the methods within the enclosing class * * the caller's class loader is not the same as or an * ancestor of the class loader for the enclosing class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of the enclosing class * * * @since 1.5 */ get enclosingMethod(): Method; /** * If this `Class` object represents a local or anonymous * class within a constructor, returns a {@link * java.lang.reflect.Constructor Constructor} object representing * the immediately enclosing constructor of the underlying * class. Returns `null` otherwise. In particular, this * method returns `null` if the underlying class is a local * or anonymous class immediately enclosed by a class or * interface declaration, instance initializer or static initializer. * * @return the immediately enclosing constructor of the underlying class, if * that class is a local or anonymous class; otherwise `null`. * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of the enclosing class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the constructors within the enclosing class * * the caller's class loader is not the same as or an * ancestor of the class loader for the enclosing class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of the enclosing class * * * @since 1.5 */ get enclosingConstructor(): Constructor; /** * If the class or interface represented by this `Class` object * is a member of another class, returns the `Class` object * representing the class in which it was declared. This method returns * null if this class or interface is not a member of any other class. If * this `Class` object represents an array class, a primitive * type, or void,then this method returns null. * * @return the declaring class for this class * @throws SecurityException * If a security manager, s, is present and the caller's * class loader is not the same as or an ancestor of the class * loader for the declaring class and invocation of {@link * SecurityManager#checkPackageAccess s.checkPackageAccess()} * denies access to the package of the declaring class * @since 1.1 */ get declaringClass(): Class; /** * Returns the immediately enclosing class of the underlying * class. If the underlying class is a top level class this * method returns `null`. * @return the immediately enclosing class of the underlying class * @throws SecurityException * If a security manager, s, is present and the caller's * class loader is not the same as or an ancestor of the class * loader for the enclosing class and invocation of {@link * SecurityManager#checkPackageAccess s.checkPackageAccess()} * denies access to the package of the enclosing class * @since 1.5 */ get enclosingClass(): Class; /** * Returns the simple name of the underlying class as given in the * source code. Returns an empty string if the underlying class is * anonymous. * * The simple name of an array is the simple name of the * component type with "[]" appended. In particular the simple * name of an array whose component type is anonymous is "[]". * * @return the simple name of the underlying class * @since 1.5 */ get simpleName(): string; /** * Return an informative string for the name of this class or interface. * * @return an informative string for the name of this class or interface * @since 1.8 */ get typeName(): string; /** * Returns the canonical name of the underlying class as * defined by The Java Language Specification. * Returns `null` if the underlying class does not have a canonical * name. Classes without canonical names include: * * a {@linkplain #isLocalClass() local class} * a {@linkplain #isAnonymousClass() anonymous class} * a {@linkplain #isHidden() hidden class} * an array whose component type does not have a canonical name * * * @return the canonical name of the underlying class if it exists, and * `null` otherwise. * @since 1.5 */ get canonicalName(): string; /** * Returns `true` if and only if the underlying class * is an anonymous class. * * @apiNote * An anonymous class is not a {@linkplain #isHidden() hidden class}. * * @return `true` if and only if this class is an anonymous class. * @since 1.5 */ isAnonymousClass(): boolean; /** * Returns `true` if and only if the underlying class * is a local class. * * @return `true` if and only if this class is a local class. * @since 1.5 */ isLocalClass(): boolean; /** * Returns `true` if and only if the underlying class * is a member class. * * @return `true` if and only if this class is a member class. * @since 1.5 */ isMemberClass(): boolean; /** * Returns an array containing `Class` objects representing all * the public classes and interfaces that are members of the class * represented by this `Class` object. This includes public * class and interface members inherited from superclasses and public class * and interface members declared by the class. This method returns an * array of length 0 if this `Class` object has no public member * classes or interfaces. This method also returns an array of length 0 if * this `Class` object represents a primitive type, an array * class, or void. * * @return the array of `Class` objects representing the public * members of this class * @throws SecurityException * If a security manager, s, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class. * * @since 1.1 */ get classes(): Class[]; /** * Returns an array containing `Field` objects reflecting all * the accessible public fields of the class or interface represented by * this `Class` object. * * If this `Class` object represents a class or interface with * no accessible public fields, then this method returns an array of length * 0. * * If this `Class` object represents a class, then this method * returns the public fields of the class and of all its superclasses and * superinterfaces. * * If this `Class` object represents an interface, then this * method returns the fields of the interface and of all its * superinterfaces. * * If this `Class` object represents an array type, a primitive * type, or void, then this method returns an array of length 0. * * The elements in the returned array are not sorted and are not in any * particular order. * * @return the array of `Field` objects representing the * public fields * @throws SecurityException * If a security manager, s, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class. * * @since 1.1 * @jls 8.2 Class Members * @jls 8.3 Field Declarations */ get fields(): Field[]; /** * Returns an array containing `Method` objects reflecting all the * public methods of the class or interface represented by this ` * Class` object, including those declared by the class or interface and * those inherited from superclasses and superinterfaces. * * If this `Class` object represents an array type, then the * returned array has a `Method` object for each of the public * methods inherited by the array type from `Object`. It does not * contain a `Method` object for `clone()`. * * If this `Class` object represents an interface then the * returned array does not contain any implicitly declared methods from * `Object`. Therefore, if no methods are explicitly declared in * this interface or any of its superinterfaces then the returned array * has length 0. (Note that a `Class` object which represents a class * always has public methods, inherited from `Object`.) * * The returned array never contains methods with names "``" * or "``". * * The elements in the returned array are not sorted and are not in any * particular order. * * Generally, the result is computed as with the following 4 step algorithm. * Let C be the class or interface represented by this `Class` object: * * A union of methods is composed of: * * C's declared public instance and static methods as returned by * {@link #getDeclaredMethods()} and filtered to include only public * methods. * If C is a class other than `Object`, then include the result * of invoking this algorithm recursively on the superclass of C. * Include the results of invoking this algorithm recursively on all * direct superinterfaces of C, but include only instance methods. * * Union from step 1 is partitioned into subsets of methods with same * signature (name, parameter types) and return type. * Within each such subset only the most specific methods are selected. * Let method M be a method from a set of methods with same signature * and return type. M is most specific if there is no such method * N != M from the same set, such that N is more specific than M. * N is more specific than M if: * * N is declared by a class and M is declared by an interface; or * N and M are both declared by classes or both by interfaces and * N's declaring type is the same as or a subtype of M's declaring type * (clearly, if M's and N's declaring types are the same type, then * M and N are the same method). * * The result of this algorithm is the union of all selected methods from * step 3. * * * @apiNote There may be more than one method with a particular name * and parameter types in a class because while the Java language forbids a * class to declare multiple methods with the same signature but different * return types, the Java virtual machine does not. This * increased flexibility in the virtual machine can be used to * implement various language features. For example, covariant * returns can be implemented with {@linkplain * java.lang.reflect.Method#isBridge bridge methods}; the bridge * method and the overriding method would have the same * signature but different return types. * * @return the array of `Method` objects representing the * public methods of this class * @throws SecurityException * If a security manager, s, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class. * * @jls 8.2 Class Members * @jls 8.4 Method Declarations * @since 1.1 */ get methods(): Method[]; /** * Returns an array containing `Constructor` objects reflecting * all the public constructors of the class represented by this * `Class` object. An array of length 0 is returned if the * class has no public constructors, or if the class is an array class, or * if the class reflects a primitive type or void. * * @apiNote * While this method returns an array of ` * Constructor` objects (that is an array of constructors from * this class), the return type of this method is ` * Constructor[]` and not `Constructor[]` as * might be expected. This less informative return type is * necessary since after being returned from this method, the * array could be modified to hold `Constructor` objects for * different classes, which would violate the type guarantees of * `Constructor[]`. * * @return the array of `Constructor` objects representing the * public constructors of this class * @throws SecurityException * If a security manager, s, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class. * * @since 1.1 */ get constructors(): Constructor[]; /** * Returns a `Field` object that reflects the specified public member * field of the class or interface represented by this `Class` * object. The `name` parameter is a `String` specifying the * simple name of the desired field. * * The field to be reflected is determined by the algorithm that * follows. Let C be the class or interface represented by this `Class` object: * * * If C declares a public field with the name specified, that is the * field to be reflected. * If no field was found in step 1 above, this algorithm is applied * recursively to each direct superinterface of C. The direct * superinterfaces are searched in the order they were declared. * If no field was found in steps 1 and 2 above, and C has a * superclass S, then this algorithm is invoked recursively upon S. * If C has no superclass, then a `NoSuchFieldException` * is thrown. * * * If this `Class` object represents an array type, then this * method does not find the `length` field of the array type. * * @param name the field name * @return the `Field` object of this class specified by * `name` * @throws NoSuchFieldException if a field with the specified name is * not found. * @throws NullPointerException if `name` is `null` * @throws SecurityException * If a security manager, s, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class. * * @since 1.1 * @jls 8.2 Class Members * @jls 8.3 Field Declarations */ getField(name: string): Field; /** * Returns a `Method` object that reflects the specified public * member method of the class or interface represented by this * `Class` object. The `name` parameter is a * `String` specifying the simple name of the desired method. The * `parameterTypes` parameter is an array of `Class` * objects that identify the method's formal parameter types, in declared * order. If `parameterTypes` is `null`, it is * treated as if it were an empty array. * * If this `Class` object represents an array type, then this * method finds any public method inherited by the array type from * `Object` except method `clone()`. * * If this `Class` object represents an interface then this * method does not find any implicitly declared method from * `Object`. Therefore, if no methods are explicitly declared in * this interface or any of its superinterfaces, then this method does not * find any method. * * This method does not find any method with name "``" or * "``". * * Generally, the method to be reflected is determined by the 4 step * algorithm that follows. * Let C be the class or interface represented by this `Class` object: * * A union of methods is composed of: * * C's declared public instance and static methods as returned by * {@link #getDeclaredMethods()} and filtered to include only public * methods that match given `name` and `parameterTypes` * If C is a class other than `Object`, then include the result * of invoking this algorithm recursively on the superclass of C. * Include the results of invoking this algorithm recursively on all * direct superinterfaces of C, but include only instance methods. * * This union is partitioned into subsets of methods with same * return type (the selection of methods from step 1 also guarantees that * they have the same method name and parameter types). * Within each such subset only the most specific methods are selected. * Let method M be a method from a set of methods with same VM * signature (return type, name, parameter types). * M is most specific if there is no such method N != M from the same * set, such that N is more specific than M. N is more specific than M * if: * * N is declared by a class and M is declared by an interface; or * N and M are both declared by classes or both by interfaces and * N's declaring type is the same as or a subtype of M's declaring type * (clearly, if M's and N's declaring types are the same type, then * M and N are the same method). * * The result of this algorithm is chosen arbitrarily from the methods * with most specific return type among all selected methods from step 3. * Let R be a return type of a method M from the set of all selected methods * from step 3. M is a method with most specific return type if there is * no such method N != M from the same set, having return type S != R, * such that S is a subtype of R as determined by * R.class.{@link #isAssignableFrom}(S.class). * * * @apiNote There may be more than one method with matching name and * parameter types in a class because while the Java language forbids a * class to declare multiple methods with the same signature but different * return types, the Java virtual machine does not. This * increased flexibility in the virtual machine can be used to * implement various language features. For example, covariant * returns can be implemented with {@linkplain * java.lang.reflect.Method#isBridge bridge methods}; the bridge * method and the overriding method would have the same * signature but different return types. This method would return the * overriding method as it would have a more specific return type. * * @param name the name of the method * @param parameterTypes the list of parameters * @return the `Method` object that matches the specified * `name` and `parameterTypes` * @throws NoSuchMethodException if a matching method is not found * or if the name is ""or "". * @throws NullPointerException if `name` is `null` * @throws SecurityException * If a security manager, s, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class. * * @jls 8.2 Class Members * @jls 8.4 Method Declarations * @since 1.1 */ getMethod(name: string, ...parameterTypes: Class[]): Method; /** * Returns a `Constructor` object that reflects the specified * public constructor of the class represented by this `Class` * object. The `parameterTypes` parameter is an array of * `Class` objects that identify the constructor's formal * parameter types, in declared order. * * If this `Class` object represents an inner class * declared in a non-static context, the formal parameter types * include the explicit enclosing instance as the first parameter. * * The constructor to reflect is the public constructor of the class * represented by this `Class` object whose formal parameter * types match those specified by `parameterTypes`. * * @param parameterTypes the parameter array * @return the `Constructor` object of the public constructor that * matches the specified `parameterTypes` * @throws NoSuchMethodException if a matching method is not found. * @throws SecurityException * If a security manager, s, is present and * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class. * * @since 1.1 */ getConstructor(...parameterTypes: Class[]): Constructor; /** * Returns an array of `Class` objects reflecting all the * classes and interfaces declared as members of the class represented by * this `Class` object. This includes public, protected, default * (package) access, and private classes and interfaces declared by the * class, but excludes inherited classes and interfaces. This method * returns an array of length 0 if the class declares no classes or * interfaces as members, or if this `Class` object represents a * primitive type, an array class, or void. * * @return the array of `Class` objects representing all the * declared members of this class * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of this class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the declared classes within this class * * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class * * * * @since 1.1 */ get declaredClasses(): Class[]; /** * Returns an array of `Field` objects reflecting all the fields * declared by the class or interface represented by this * `Class` object. This includes public, protected, default * (package) access, and private fields, but excludes inherited fields. * * If this `Class` object represents a class or interface with no * declared fields, then this method returns an array of length 0. * * If this `Class` object represents an array type, a primitive * type, or void, then this method returns an array of length 0. * * The elements in the returned array are not sorted and are not in any * particular order. * * @return the array of `Field` objects representing all the * declared fields of this class * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of this class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the declared fields within this class * * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class * * * * @since 1.1 * @jls 8.2 Class Members * @jls 8.3 Field Declarations */ get declaredFields(): Field[]; /** * Returns an array of `RecordComponent` objects representing all the * record components of this record class, or `null` if this class is * not a record class. * * The components are returned in the same order that they are declared * in the record header. The array is empty if this record class has no * components. If the class is not a record class, that is {@link * #isRecord()} returns `false`, then this method returns `null`. * Conversely, if {@link #isRecord()} returns `true`, then this method * returns a non-null value. * * @return An array of `RecordComponent` objects representing all the * record components of this record class, or `null` if this * class is not a record class * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of this class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the declared methods within this class * * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class * * * * @jls 8.10 Record Classes * @since 16 */ get recordComponents(): RecordComponent[]; /** * Returns an array containing `Method` objects reflecting all the * declared methods of the class or interface represented by this ` * Class` object, including public, protected, default (package) * access, and private methods, but excluding inherited methods. * * If this `Class` object represents a class or interface that * has multiple declared methods with the same name and parameter types, * but different return types, then the returned array has a `Method` * object for each such method. * * If this `Class` object represents a class or interface that * has a class initialization method ``, then the returned * array does not have a corresponding `Method` object. * * If this `Class` object represents a class or interface with no * declared methods, then the returned array has length 0. * * If this `Class` object represents an array type, a primitive * type, or void, then the returned array has length 0. * * The elements in the returned array are not sorted and are not in any * particular order. * * @return the array of `Method` objects representing all the * declared methods of this class * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of this class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the declared methods within this class * * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class * * * * @jls 8.2 Class Members * @jls 8.4 Method Declarations * @since 1.1 */ get declaredMethods(): Method[]; /** * Returns an array of `Constructor` objects reflecting all the * constructors declared by the class represented by this * `Class` object. These are public, protected, default * (package) access, and private constructors. The elements in the array * returned are not sorted and are not in any particular order. If the * class has a default constructor, it is included in the returned array. * This method returns an array of length 0 if this `Class` * object represents an interface, a primitive type, an array class, or * void. * * See The Java Language Specification, * section {@jls 8.2}. * * @return the array of `Constructor` objects representing all the * declared constructors of this class * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of this class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the declared constructors within this class * * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class * * * * @since 1.1 */ get declaredConstructors(): Constructor[]; /** * Returns a `Field` object that reflects the specified declared * field of the class or interface represented by this `Class` * object. The `name` parameter is a `String` that specifies * the simple name of the desired field. * * If this `Class` object represents an array type, then this * method does not find the `length` field of the array type. * * @param name the name of the field * @return the `Field` object for the specified field in this * class * @throws NoSuchFieldException if a field with the specified name is * not found. * @throws NullPointerException if `name` is `null` * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of this class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the declared field * * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class * * * * @since 1.1 * @jls 8.2 Class Members * @jls 8.3 Field Declarations */ getDeclaredField(name: string): Field; /** * Returns a `Method` object that reflects the specified * declared method of the class or interface represented by this * `Class` object. The `name` parameter is a * `String` that specifies the simple name of the desired * method, and the `parameterTypes` parameter is an array of * `Class` objects that identify the method's formal parameter * types, in declared order. If more than one method with the same * parameter types is declared in a class, and one of these methods has a * return type that is more specific than any of the others, that method is * returned; otherwise one of the methods is chosen arbitrarily. If the * name is ""or "" a `NoSuchMethodException` * is raised. * * If this `Class` object represents an array type, then this * method does not find the `clone()` method. * * @param name the name of the method * @param parameterTypes the parameter array * @return the `Method` object for the method of this class * matching the specified name and parameters * @throws NoSuchMethodException if a matching method is not found. * @throws NullPointerException if `name` is `null` * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of this class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the declared method * * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class * * * * @jls 8.2 Class Members * @jls 8.4 Method Declarations * @since 1.1 */ getDeclaredMethod(name: string, ...parameterTypes: Class[]): Method; /** * Returns a `Constructor` object that reflects the specified * constructor of the class or interface represented by this * `Class` object. The `parameterTypes` parameter is * an array of `Class` objects that identify the constructor's * formal parameter types, in declared order. * * If this `Class` object represents an inner class * declared in a non-static context, the formal parameter types * include the explicit enclosing instance as the first parameter. * * @param parameterTypes the parameter array * @return The `Constructor` object for the constructor with the * specified parameter list * @throws NoSuchMethodException if a matching method is not found. * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: * * * * the caller's class loader is not the same as the * class loader of this class and invocation of * {@link SecurityManager#checkPermission * s.checkPermission} method with * `RuntimePermission("accessDeclaredMembers")` * denies access to the declared constructor * * the caller's class loader is not the same as or an * ancestor of the class loader for the current class and * invocation of {@link SecurityManager#checkPackageAccess * s.checkPackageAccess()} denies access to the package * of this class * * * * @since 1.1 */ getDeclaredConstructor(...parameterTypes: Class[]): Constructor; /** * Finds a resource with a given name. * * If this class is in a named {@link Module Module} then this method * will attempt to find the resource in the module. This is done by * delegating to the module's class loader {@link * ClassLoader#findResource(String,String) findResource(String,String)} * method, invoking it with the module name and the absolute name of the * resource. Resources in named modules are subject to the rules for * encapsulation specified in the `Module` {@link * Module#getResourceAsStream getResourceAsStream} method and so this * method returns `null` when the resource is a * non-"`.class`" resource in a package that is not open to the * caller's module. * * Otherwise, if this class is not in a named module then the rules for * searching resources associated with a given class are implemented by the * defining {@linkplain ClassLoader class loader} of the class. This method * delegates to this `Class` object's class loader. * If this `Class` object was loaded by the bootstrap class loader, * the method delegates to {@link ClassLoader#getSystemResourceAsStream}. * * Before delegation, an absolute resource name is constructed from the * given resource name using this algorithm: * * * * If the `name` begins with a `'/'` * ('\u002f'), then the absolute name of the resource is the * portion of the `name` following the `'/'`. * * Otherwise, the absolute name is of the following form: * * * `modified_package_name/name` * * * Where the `modified_package_name` is the package name of this * object with `'/'` substituted for `'.'` * ('\u002e'). * * * * @param name name of the desired resource * @return A {@link java.io.InputStream} object; `null` if no * resource with this name is found, the resource is in a package * that is not {@linkplain Module#isOpen(String, Module) open} to at * least the caller module, or access to the resource is denied * by the security manager. * @throws NullPointerException If `name` is `null` * * @see Module#getResourceAsStream(String) * @since 1.1 * @revised 9 */ getResourceAsStream(name: string): InputStream; /** * Finds a resource with a given name. * * If this class is in a named {@link Module Module} then this method * will attempt to find the resource in the module. This is done by * delegating to the module's class loader {@link * ClassLoader#findResource(String,String) findResource(String,String)} * method, invoking it with the module name and the absolute name of the * resource. Resources in named modules are subject to the rules for * encapsulation specified in the `Module` {@link * Module#getResourceAsStream getResourceAsStream} method and so this * method returns `null` when the resource is a * non-"`.class`" resource in a package that is not open to the * caller's module. * * Otherwise, if this class is not in a named module then the rules for * searching resources associated with a given class are implemented by the * defining {@linkplain ClassLoader class loader} of the class. This method * delegates to this `Class` object's class loader. * If this `Class` object was loaded by the bootstrap class loader, * the method delegates to {@link ClassLoader#getSystemResource}. * * Before delegation, an absolute resource name is constructed from the * given resource name using this algorithm: * * * * If the `name` begins with a `'/'` * ('\u002f'), then the absolute name of the resource is the * portion of the `name` following the `'/'`. * * Otherwise, the absolute name is of the following form: * * * `modified_package_name/name` * * * Where the `modified_package_name` is the package name of this * object with `'/'` substituted for `'.'` * ('\u002e'). * * * * @param name name of the desired resource * @return A {@link java.net.URL} object; `null` if no resource with * this name is found, the resource cannot be located by a URL, the * resource is in a package that is not * {@linkplain Module#isOpen(String, Module) open} to at least the caller * module, or access to the resource is denied by the security * manager. * @throws NullPointerException If `name` is `null` * @since 1.1 * @revised 9 */ getResource(name: string): URL; /** * Returns the `ProtectionDomain` of this class. If there is a * security manager installed, this method first calls the security * manager's `checkPermission` method with a * `RuntimePermission("getProtectionDomain")` permission to * ensure it's ok to get the * `ProtectionDomain`. * * @return the ProtectionDomain of this class * * @throws SecurityException * if a security manager exists and its * `checkPermission` method doesn't allow * getting the ProtectionDomain. * * @see java.security.ProtectionDomain * @see SecurityManager#checkPermission * @see java.lang.RuntimePermission * @since 1.2 */ get protectionDomain(): ProtectionDomain; /** * Returns the assertion status that would be assigned to this * class if it were to be initialized at the time this method is invoked. * If this class has had its assertion status set, the most recent * setting will be returned; otherwise, if any package default assertion * status pertains to this class, the most recent setting for the most * specific pertinent package default assertion status is returned; * otherwise, if this class is not a system class (i.e., it has a * class loader) its class loader's default assertion status is returned; * otherwise, the system class default assertion status is returned. * * @apiNote * Few programmers will have any need for this method; it is provided * for the benefit of the JDK itself. (It allows a class to determine at * the time that it is initialized whether assertions should be enabled.) * Note that this method is not guaranteed to return the actual * assertion status that was (or will be) associated with the specified * class when it was (or will be) initialized. * * @return the desired assertion status of the specified class. * @see java.lang.ClassLoader#setClassAssertionStatus * @see java.lang.ClassLoader#setPackageAssertionStatus * @see java.lang.ClassLoader#setDefaultAssertionStatus * @since 1.4 */ desiredAssertionStatus(): boolean; /** * Returns true if and only if this class was declared as an enum in the * source code. * * Note that {@link java.lang.Enum} is not itself an enum class. * * Also note that if an enum constant is declared with a class body, * the class of that enum constant object is an anonymous class * and not the class of the declaring enum class. The * {@link Enum#getDeclaringClass} method of an enum constant can * be used to get the class of the enum class declaring the * constant. * * @return true if and only if this class was declared as an enum in the * source code * @since 1.5 * @jls 8.9.1 Enum Constants */ isEnum(): boolean; /** * Returns `true` if and only if this class is a record class. * * The {@linkplain #getSuperclass() direct superclass} of a record * class is `java.lang.Record`. A record class is {@linkplain * Modifier#FINAL final}. A record class has (possibly zero) record * components; {@link #getRecordComponents()} returns a non-null but * possibly empty value for a record. * * Note that class {@link Record} is not a record class and thus * invoking this method on class `Record` returns `false`. * * @return true if and only if this class is a record class, otherwise false * @jls 8.10 Record Classes * @since 16 */ isRecord(): boolean; /** * Returns the elements of this enum class or null if this * Class object does not represent an enum class. * * @return an array containing the values comprising the enum class * represented by this `Class` object in the order they're * declared, or null if this `Class` object does not * represent an enum class * @since 1.5 */ get enumConstants(): T[]; /** * Casts an object to the class or interface represented * by this `Class` object. * * @param obj the object to be cast * @return the object after casting, or null if obj is null * * @throws ClassCastException if the object is not * null and is not assignable to the type T. * * @since 1.5 */ cast(obj: any): T; /** * Casts this `Class` object to represent a subclass of the class * represented by the specified class object. Checks that the cast * is valid, and throws a `ClassCastException` if it is not. If * this method succeeds, it always returns a reference to this `Class` object. * * This method is useful when a client needs to "narrow" the type of * a `Class` object to pass it to an API that restricts the * `Class` objects that it is willing to accept. A cast would * generate a compile-time warning, as the correctness of the cast * could not be checked at runtime (because generic types are implemented * by erasure). * * @param the type to cast this `Class` object to * @param clazz the class of the type to cast this `Class` object to * @return this `Class` object, cast to represent a subclass of * the specified class object. * @throws ClassCastException if this `Class` object does not * represent a subclass of the specified class (here "subclass" includes * the class itself). * @since 1.5 */ asSubclass(clazz: Class): Class; /** * {@inheritDoc} * Note that any annotation returned by this method is a * declaration annotation. * * @throws NullPointerException {@inheritDoc} * @since 1.5 */ getAnnotation(annotationClass: Class): A; /** * {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @since 1.5 */ isAnnotationPresent(annotationClass: Class): boolean; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. * * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getAnnotationsByType(annotationClass: Class): A[]; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. * * @since 1.5 */ get annotations(): Annotation[]; /** * {@inheritDoc} * Note that any annotation returned by this method is a * declaration annotation. * * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getDeclaredAnnotation(annotationClass: Class): A; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. * * @throws NullPointerException {@inheritDoc} * @since 1.8 */ getDeclaredAnnotationsByType(annotationClass: Class): A[]; /** * {@inheritDoc} * Note that any annotations returned by this method are * declaration annotations. * * @since 1.5 */ get declaredAnnotations(): Annotation[]; /** * Returns an `AnnotatedType` object that represents the use of a * type to specify the superclass of the entity represented by this ` * Class` object. (The use of type Foo to specify the superclass * in '... extends Foo' is distinct from the declaration of class * Foo.) * * If this `Class` object represents a class whose declaration * does not explicitly indicate an annotated superclass, then the return * value is an `AnnotatedType` object representing an element with no * annotations. * * If this `Class` represents either the `Object` class, an * interface type, an array type, a primitive type, or void, the return * value is `null`. * * @return an object representing the superclass * @since 1.8 */ get annotatedSuperclass(): AnnotatedType; /** * Returns an array of `AnnotatedType` objects that represent the use * of types to specify superinterfaces of the entity represented by this * `Class` object. (The use of type Foo to specify a * superinterface in '... implements Foo' is distinct from the * declaration of interface Foo.) * * If this `Class` object represents a class, the return value is * an array containing objects representing the uses of interface types to * specify interfaces implemented by the class. The order of the objects in * the array corresponds to the order of the interface types used in the * 'implements' clause of the declaration of this `Class` object. * * If this `Class` object represents an interface, the return * value is an array containing objects representing the uses of interface * types to specify interfaces directly extended by the interface. The * order of the objects in the array corresponds to the order of the * interface types used in the 'extends' clause of the declaration of this * `Class` object. * * If this `Class` object represents a class or interface whose * declaration does not explicitly indicate any annotated superinterfaces, * the return value is an array of length 0. * * If this `Class` object represents either the `Object` * class, an array type, a primitive type, or void, the return value is an * array of length 0. * * @return an array representing the superinterfaces * @since 1.8 */ get annotatedInterfaces(): AnnotatedType[]; /** * Returns the nest host of the nest to which the class * or interface represented by this `Class` object belongs. * Every class and interface belongs to exactly one nest. * * If the nest host of this class or interface has previously * been determined, then this method returns the nest host. * If the nest host of this class or interface has * not previously been determined, then this method determines the nest * host using the algorithm of JVMS 5.4.4, and returns it. * * Often, a class or interface belongs to a nest consisting only of itself, * in which case this method returns `this` to indicate that the class * or interface is the nest host. * * If this `Class` object represents a primitive type, an array type, * or `void`, then this method returns `this`, * indicating that the represented entity belongs to the nest consisting only of * itself, and is the nest host. * * @return the nest host of this class or interface * * @throws SecurityException * If the returned class is not the current class, and * if a security manager, s, is present and the caller's * class loader is not the same as or an ancestor of the class * loader for the returned class and invocation of {@link * SecurityManager#checkPackageAccess s.checkPackageAccess()} * denies access to the package of the returned class * @since 11 * @jvms 4.7.28 The `NestHost` Attribute * @jvms 4.7.29 The `NestMembers` Attribute * @jvms 5.4.4 Access Control */ get nestHost(): Class; /** * Determines if the given `Class` is a nestmate of the * class or interface represented by this `Class` object. * Two classes or interfaces are nestmates * if they have the same {@linkplain #getNestHost() nest host}. * * @param c the class to check * @return `true` if this class and `c` are members of * the same nest; and `false` otherwise. * * @since 11 */ isNestmateOf(c: Class): boolean; /** * Returns an array containing `Class` objects representing all the * classes and interfaces that are members of the nest to which the class * or interface represented by this `Class` object belongs. * * First, this method obtains the {@linkplain #getNestHost() nest host}, * `H`, of the nest to which the class or interface represented by * this `Class` object belongs. The zeroth element of the returned * array is `H`. * * Then, for each class or interface `C` which is recorded by `H` * as being a member of its nest, this method attempts to obtain the `Class` * object for `C` (using {@linkplain #getClassLoader() the defining class * loader} of the current `Class` object), and then obtains the * {@linkplain #getNestHost() nest host} of the nest to which `C` belongs. * The classes and interfaces which are recorded by `H` as being members * of its nest, and for which `H` can be determined as their nest host, * are indicated by subsequent elements of the returned array. The order of * such elements is unspecified. Duplicates are permitted. * * If this `Class` object represents a primitive type, an array type, * or `void`, then this method returns a single-element array containing * `this`. * * @apiNote * The returned array includes only the nest members recorded in the `NestMembers` * attribute, and not any hidden classes that were added to the nest via * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...) * Lookup::defineHiddenClass}. * * @return an array of all classes and interfaces in the same nest as * this class or interface * * @throws SecurityException * If any returned class is not the current class, and * if a security manager, s, is present and the caller's * class loader is not the same as or an ancestor of the class * loader for that returned class and invocation of {@link * SecurityManager#checkPackageAccess s.checkPackageAccess()} * denies access to the package of that returned class * * @since 11 * @see #getNestHost() * @jvms 4.7.28 The `NestHost` Attribute * @jvms 4.7.29 The `NestMembers` Attribute */ get nestMembers(): Class[]; /** * Returns the descriptor string of the entity (class, interface, array class, * primitive type, or `void`) represented by this `Class` object. * * If this `Class` object represents a class or interface, * not an array class, then: * * If the class or interface is not {@linkplain Class#isHidden() hidden}, * then the result is a field descriptor (JVMS {@jvms 4.3.2}) * for the class or interface. Calling * {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor} * with the result descriptor string produces a {@link ClassDesc ClassDesc} * describing this class or interface. * If the class or interface is {@linkplain Class#isHidden() hidden}, * then the result is a string of the form: * * `"L" +` N `+ "." + + ";"` * * where N is the binary name * encoded in internal form indicated by the `class` file passed to * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...) * Lookup::defineHiddenClass}, and `` is an unqualified name. * A hidden class or interface has no {@linkplain ClassDesc nominal descriptor}. * The result string is not a type descriptor. * * * If this `Class` object represents an array class, then * the result is a string consisting of one or more '`[`' characters * representing the depth of the array nesting, followed by the * descriptor string of the element type. * * If the element type is not a {@linkplain Class#isHidden() hidden} class * or interface, then this array class can be described nominally. * Calling {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor} * with the result descriptor string produces a {@link ClassDesc ClassDesc} * describing this array class. * If the element type is a {@linkplain Class#isHidden() hidden} class or * interface, then this array class cannot be described nominally. * The result string is not a type descriptor. * * * If this `Class` object represents a primitive type or * `void`, then the result is a field descriptor string which * is a one-letter code corresponding to a primitive type or `void` * (`"B", "C", "D", "F", "I", "J", "S", "Z", "V"`) (JVMS {@jvms 4.3.2}). * * @apiNote * This is not a strict inverse of {@link #forName}; * distinct classes which share a common name but have different class loaders * will have identical descriptor strings. * * @return the descriptor string for this `Class` object * @jvms 4.3.2 Field Descriptors * @since 12 */ descriptorString(): string; /** * Returns a `Class` for an array type whose component type * is described by this {@linkplain Class}. * * @return a `Class` describing the array type * @since 12 */ arrayType(): Class; /** * Returns a nominal descriptor for this instance, if one can be * constructed, or an empty {@link Optional} if one cannot be. * * @return An {@link Optional} containing the resulting nominal descriptor, * or an empty {@link Optional} if one cannot be constructed. * @since 12 */ describeConstable(): Optional; /** * Returns `true` if and only if the underlying class is a hidden class. * * @return `true` if and only if this class is a hidden class. * * @since 15 * @see MethodHandles.Lookup#defineHiddenClass */ isHidden(): boolean; /** * {@preview Associated with sealed classes, a preview feature of the Java language. * * This method is associated with sealed classes, a preview * feature of the Java language. Preview features * may be removed in a future release, or upgraded to permanent * features of the Java language.} * * Returns an array containing `Class` objects representing the * direct subinterfaces or subclasses permitted to extend or * implement this class or interface if it is sealed. The order of such elements * is unspecified. The array is empty if this sealed class or interface has no * permitted subclass. If this `Class` object represents a primitive type, * `void`, an array type, or a class or interface that is not sealed, * that is {@link #isSealed()} returns `false`, then this method returns `null`. * Conversely, if {@link #isSealed()} returns `true`, then this method * returns a non-null value. * * For each class or interface `C` which is recorded as a permitted * direct subinterface or subclass of this class or interface, * this method attempts to obtain the `Class` * object for `C` (using {@linkplain #getClassLoader() the defining class * loader} of the current `Class` object). * The `Class` objects which can be obtained and which are direct * subinterfaces or subclasses of this class or interface, * are indicated by elements of the returned array. If a `Class` object * cannot be obtained, it is silently ignored, and not included in the result * array. * * @return an array of `Class` objects of the permitted subclasses of this class or interface, * or `null` if this class or interface is not sealed. * * @throws SecurityException * If a security manager, s, is present and the caller's * class loader is not the same as or an ancestor of the class * loader for that returned class and invocation of {@link * SecurityManager#checkPackageAccess s.checkPackageAccess()} * denies access to the package of any class in the returned array. * * @jls 8.1 Class Declarations * @jls 9.1 Interface Declarations * @since 15 */ get permittedSubclasses(): Class[]; /** * {@preview Associated with sealed classes, a preview feature of the Java language. * * This method is associated with sealed classes, a preview * feature of the Java language. Preview features * may be removed in a future release, or upgraded to permanent * features of the Java language.} * * Returns `true` if and only if this `Class` object represents * a sealed class or interface. If this `Class` object represents a * primitive type, `void`, or an array type, this method returns * `false`. A sealed class or interface has (possibly zero) permitted * subclasses; {@link #getPermittedSubclasses()} returns a non-null but * possibly empty value for a sealed class or interface. * * @return `true` if and only if this `Class` object represents a sealed class or interface. * * @jls 8.1 Class Declarations * @jls 9.1 Interface Declarations * @since 15 */ isSealed(): boolean; } export interface Class extends Serializable, GenericDeclaration, Type, AnnotatedElement, OfField>, Constable {} /** * Thrown if the Java Virtual Machine cannot find an appropriate * native-language definition of a method declared `native`. * * @see java.lang.Runtime * @since 1.0 */ export class UnsatisfiedLinkError extends LinkageError { /** * Constructs an `UnsatisfiedLinkError` with no detail message. */ constructor(); /** * Constructs an `UnsatisfiedLinkError` with the * specified detail message. * * @param s the detail message. */ constructor(s: string); } /** * Thrown when the Java Virtual Machine detects a circularity in the * superclass hierarchy of a class being loaded. * * @since 1.0 */ export class ClassCircularityError extends LinkageError { /** * Constructs a `ClassCircularityError` with no detail message. */ constructor(); /** * Constructs a `ClassCircularityError` with the specified detail * message. * * @param s * The detail message */ constructor(s: string); } export class Runtime { /** * Returns the runtime object associated with the current Java application. * Most of the methods of class `Runtime` are instance * methods and must be invoked with respect to the current runtime object. * * @return the `Runtime` object associated with the current * Java application. */ static get runtime(): Runtime; /** * Terminates the currently running Java virtual machine by initiating its * shutdown sequence. This method never returns normally. The argument * serves as a status code; by convention, a nonzero status code indicates * abnormal termination. * * All registered {@linkplain #addShutdownHook shutdown hooks}, if any, * are started in some unspecified order and allowed to run concurrently * until they finish. Once this is done the virtual machine * {@linkplain #halt halts}. * * If this method is invoked after all shutdown hooks have already * been run and the status is nonzero then this method halts the * virtual machine with the given status code. Otherwise, this method * blocks indefinitely. * * The {@link System#exit(int) System.exit} method is the * conventional and convenient means of invoking this method. * * @param status * Termination status. By convention, a nonzero status code * indicates abnormal termination. * * @throws SecurityException * If a security manager is present and its * {@link SecurityManager#checkExit checkExit} method does not permit * exiting with the specified status * * @see java.lang.SecurityException * @see java.lang.SecurityManager#checkExit(int) * @see #addShutdownHook * @see #removeShutdownHook * @see #halt(int) */ exit(status: number): void; /** * Registers a new virtual-machine shutdown hook. * * The Java virtual machine shuts down in response to two kinds * of events: * * * * The program exits normally, when the last non-daemon * thread exits or when the {@link #exit exit} (equivalently, * {@link System#exit(int) System.exit}) method is invoked, or * * The virtual machine is terminated in response to a * user interrupt, such as typing `^C`, or a system-wide event, * such as user logoff or system shutdown. * * * * A shutdown hook is simply an initialized but unstarted * thread. When the virtual machine begins its shutdown sequence it will * start all registered shutdown hooks in some unspecified order and let * them run concurrently. When all the hooks have finished it will then * halt. Note that daemon threads will continue to run during the shutdown * sequence, as will non-daemon threads if shutdown was initiated by * invoking the {@link #exit exit} method. * * Once the shutdown sequence has begun it can be stopped only by * invoking the {@link #halt halt} method, which forcibly * terminates the virtual machine. * * Once the shutdown sequence has begun it is impossible to register a * new shutdown hook or de-register a previously-registered hook. * Attempting either of these operations will cause an * {@link IllegalStateException} to be thrown. * * Shutdown hooks run at a delicate time in the life cycle of a virtual * machine and should therefore be coded defensively. They should, in * particular, be written to be thread-safe and to avoid deadlocks insofar * as possible. They should also not rely blindly upon services that may * have registered their own shutdown hooks and therefore may themselves in * the process of shutting down. Attempts to use other thread-based * services such as the AWT event-dispatch thread, for example, may lead to * deadlocks. * * Shutdown hooks should also finish their work quickly. When a * program invokes {@link #exit exit} the expectation is * that the virtual machine will promptly shut down and exit. When the * virtual machine is terminated due to user logoff or system shutdown the * underlying operating system may only allow a fixed amount of time in * which to shut down and exit. It is therefore inadvisable to attempt any * user interaction or to perform a long-running computation in a shutdown * hook. * * Uncaught exceptions are handled in shutdown hooks just as in any * other thread, by invoking the * {@link ThreadGroup#uncaughtException uncaughtException} method of the * thread's {@link ThreadGroup} object. The default implementation of this * method prints the exception's stack trace to {@link System#err} and * terminates the thread; it does not cause the virtual machine to exit or * halt. * * In rare circumstances the virtual machine may abort, that is, * stop running without shutting down cleanly. This occurs when the * virtual machine is terminated externally, for example with the * `SIGKILL` signal on Unix or the `TerminateProcess` call on * Microsoft Windows. The virtual machine may also abort if a native * method goes awry by, for example, corrupting internal data structures or * attempting to access nonexistent memory. If the virtual machine aborts * then no guarantee can be made about whether or not any shutdown hooks * will be run. * * @param hook * An initialized but unstarted {@link Thread} object * * @throws IllegalArgumentException * If the specified hook has already been registered, * or if it can be determined that the hook is already running or * has already been run * * @throws IllegalStateException * If the virtual machine is already in the process * of shutting down * * @throws SecurityException * If a security manager is present and it denies * {@link RuntimePermission}("shutdownHooks") * * @see #removeShutdownHook * @see #halt(int) * @see #exit(int) * @since 1.3 */ addShutdownHook(hook: Thread): void; /** * De-registers a previously-registered virtual-machine shutdown hook. * * @param hook the hook to remove * @return `true` if the specified hook had previously been * registered and was successfully de-registered, `false` * otherwise. * * @throws IllegalStateException * If the virtual machine is already in the process of shutting * down * * @throws SecurityException * If a security manager is present and it denies * {@link RuntimePermission}("shutdownHooks") * * @see #addShutdownHook * @see #exit(int) * @since 1.3 */ removeShutdownHook(hook: Thread): boolean; /** * Forcibly terminates the currently running Java virtual machine. This * method never returns normally. * * This method should be used with extreme caution. Unlike the * {@link #exit exit} method, this method does not cause shutdown * hooks to be started. If the shutdown sequence has already been * initiated then this method does not wait for any running * shutdown hooks to finish their work. * * @param status * Termination status. By convention, a nonzero status code * indicates abnormal termination. If the {@link Runtime#exit exit} * (equivalently, {@link System#exit(int) System.exit}) method * has already been invoked then this status code * will override the status code passed to that method. * * @throws SecurityException * If a security manager is present and its * {@link SecurityManager#checkExit checkExit} method * does not permit an exit with the specified status * * @see #exit * @see #addShutdownHook * @see #removeShutdownHook * @since 1.3 */ halt(status: number): void; /** * Executes the specified string command in a separate process. * * This is a convenience method. An invocation of the form * `exec(command)` * behaves in exactly the same way as the invocation * {@link #exec(String, String[], File) exec}`(command, null, null)`. * * @param command a specified system command. * * @return A new {@link Process} object for managing the subprocess * * @throws SecurityException * If a security manager exists and its * {@link SecurityManager#checkExec checkExec} * method doesn't allow creation of the subprocess * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If `command` is `null` * * @throws IllegalArgumentException * If `command` is empty * * @see #exec(String[], String[], File) * @see ProcessBuilder */ exec(command: string): Process; /** * Executes the specified string command in a separate process with the * specified environment. * * This is a convenience method. An invocation of the form * `exec(command, envp)` * behaves in exactly the same way as the invocation * {@link #exec(String, String[], File) exec}`(command, envp, null)`. * * @param command a specified system command. * * @param envp array of strings, each element of which * has environment variable settings in the format * name=value, or * `null` if the subprocess should inherit * the environment of the current process. * * @return A new {@link Process} object for managing the subprocess * * @throws SecurityException * If a security manager exists and its * {@link SecurityManager#checkExec checkExec} * method doesn't allow creation of the subprocess * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If `command` is `null`, * or one of the elements of `envp` is `null` * * @throws IllegalArgumentException * If `command` is empty * * @see #exec(String[], String[], File) * @see ProcessBuilder */ exec(command: string, envp: string[]): Process; /** * Executes the specified string command in a separate process with the * specified environment and working directory. * * This is a convenience method. An invocation of the form * `exec(command, envp, dir)` * behaves in exactly the same way as the invocation * {@link #exec(String[], String[], File) exec}`(cmdarray, envp, dir)`, * where `cmdarray` is an array of all the tokens in * `command`. * * More precisely, the `command` string is broken * into tokens using a {@link StringTokenizer} created by the call * `new {@link StringTokenizer`(command)} with no * further modification of the character categories. The tokens * produced by the tokenizer are then placed in the new string * array `cmdarray`, in the same order. * * @param command a specified system command. * * @param envp array of strings, each element of which * has environment variable settings in the format * name=value, or * `null` if the subprocess should inherit * the environment of the current process. * * @param dir the working directory of the subprocess, or * `null` if the subprocess should inherit * the working directory of the current process. * * @return A new {@link Process} object for managing the subprocess * * @throws SecurityException * If a security manager exists and its * {@link SecurityManager#checkExec checkExec} * method doesn't allow creation of the subprocess * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If `command` is `null`, * or one of the elements of `envp` is `null` * * @throws IllegalArgumentException * If `command` is empty * * @see ProcessBuilder * @since 1.3 */ exec(command: string, envp: string[], dir: File): Process; /** * Executes the specified command and arguments in a separate process. * * This is a convenience method. An invocation of the form * `exec(cmdarray)` * behaves in exactly the same way as the invocation * {@link #exec(String[], String[], File) exec}`(cmdarray, null, null)`. * * @param cmdarray array containing the command to call and * its arguments. * * @return A new {@link Process} object for managing the subprocess * * @throws SecurityException * If a security manager exists and its * {@link SecurityManager#checkExec checkExec} * method doesn't allow creation of the subprocess * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If `cmdarray` is `null`, * or one of the elements of `cmdarray` is `null` * * @throws IndexOutOfBoundsException * If `cmdarray` is an empty array * (has length `0`) * * @see ProcessBuilder */ exec(cmdarray: string[]): Process; /** * Executes the specified command and arguments in a separate process * with the specified environment. * * This is a convenience method. An invocation of the form * `exec(cmdarray, envp)` * behaves in exactly the same way as the invocation * {@link #exec(String[], String[], File) exec}`(cmdarray, envp, null)`. * * @param cmdarray array containing the command to call and * its arguments. * * @param envp array of strings, each element of which * has environment variable settings in the format * name=value, or * `null` if the subprocess should inherit * the environment of the current process. * * @return A new {@link Process} object for managing the subprocess * * @throws SecurityException * If a security manager exists and its * {@link SecurityManager#checkExec checkExec} * method doesn't allow creation of the subprocess * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If `cmdarray` is `null`, * or one of the elements of `cmdarray` is `null`, * or one of the elements of `envp` is `null` * * @throws IndexOutOfBoundsException * If `cmdarray` is an empty array * (has length `0`) * * @see ProcessBuilder */ exec(cmdarray: string[], envp: string[]): Process; /** * Executes the specified command and arguments in a separate process with * the specified environment and working directory. * * Given an array of strings `cmdarray`, representing the * tokens of a command line, and an array of strings `envp`, * representing "environment" variable settings, this method creates * a new process in which to execute the specified command. * * This method checks that `cmdarray` is a valid operating * system command. Which commands are valid is system-dependent, * but at the very least the command must be a non-empty list of * non-null strings. * * If `envp` is `null`, the subprocess inherits the * environment settings of the current process. * * A minimal set of system dependent environment variables may * be required to start a process on some operating systems. * As a result, the subprocess may inherit additional environment variable * settings beyond those in the specified environment. * * {@link ProcessBuilder#start()} is now the preferred way to * start a process with a modified environment. * * The working directory of the new subprocess is specified by `dir`. * If `dir` is `null`, the subprocess inherits the * current working directory of the current process. * * If a security manager exists, its * {@link SecurityManager#checkExec checkExec} * method is invoked with the first component of the array * `cmdarray` as its argument. This may result in a * {@link SecurityException} being thrown. * * Starting an operating system process is highly system-dependent. * Among the many things that can go wrong are: * * The operating system program file was not found. * Access to the program file was denied. * The working directory does not exist. * * * In such cases an exception will be thrown. The exact nature * of the exception is system-dependent, but it will always be a * subclass of {@link IOException}. * * If the operating system does not support the creation of * processes, an {@link UnsupportedOperationException} will be thrown. * * * @param cmdarray array containing the command to call and * its arguments. * * @param envp array of strings, each element of which * has environment variable settings in the format * name=value, or * `null` if the subprocess should inherit * the environment of the current process. * * @param dir the working directory of the subprocess, or * `null` if the subprocess should inherit * the working directory of the current process. * * @return A new {@link Process} object for managing the subprocess * * @throws SecurityException * If a security manager exists and its * {@link SecurityManager#checkExec checkExec} * method doesn't allow creation of the subprocess * * @throws UnsupportedOperationException * If the operating system does not support the creation of processes. * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If `cmdarray` is `null`, * or one of the elements of `cmdarray` is `null`, * or one of the elements of `envp` is `null` * * @throws IndexOutOfBoundsException * If `cmdarray` is an empty array * (has length `0`) * * @see ProcessBuilder * @since 1.3 */ exec(cmdarray: string[], envp: string[], dir: File): Process; /** * Returns the number of processors available to the Java virtual machine. * * This value may change during a particular invocation of the virtual * machine. Applications that are sensitive to the number of available * processors should therefore occasionally poll this property and adjust * their resource usage appropriately. * * @return the maximum number of processors available to the virtual * machine; never smaller than one * @since 1.4 */ availableProcessors(): number; /** * Returns the amount of free memory in the Java Virtual Machine. * Calling the * `gc` method may result in increasing the value returned * by `freeMemory.` * * @return an approximation to the total amount of memory currently * available for future allocated objects, measured in bytes. */ freeMemory(): number; /** * Returns the total amount of memory in the Java virtual machine. * The value returned by this method may vary over time, depending on * the host environment. * * Note that the amount of memory required to hold an object of any * given type may be implementation-dependent. * * @return the total amount of memory currently available for current * and future objects, measured in bytes. */ totalMemory(): number; /** * Returns the maximum amount of memory that the Java virtual machine * will attempt to use. If there is no inherent limit then the value * {@link java.lang.Long#MAX_VALUE} will be returned. * * @return the maximum amount of memory that the virtual machine will * attempt to use, measured in bytes * @since 1.4 */ maxMemory(): number; /** * Runs the garbage collector in the Java Virtual Machine. * * Calling this method suggests that the Java Virtual Machine * expend effort toward recycling unused objects in order to * make the memory they currently occupy available for reuse * by the Java Virtual Machine. * When control returns from the method call, the Java Virtual Machine * has made a best effort to reclaim space from all unused objects. * There is no guarantee that this effort will recycle any particular * number of unused objects, reclaim any particular amount of space, or * complete at any particular time, if at all, before the method returns or ever. * * The name `gc` stands for "garbage * collector". The Java Virtual Machine performs this recycling * process automatically as needed, in a separate thread, even if the * `gc` method is not invoked explicitly. * * The method {@link System#gc()} is the conventional and convenient * means of invoking this method. */ gc(): void; /** * Runs the finalization methods of any objects pending finalization. * Calling this method suggests that the Java virtual machine expend * effort toward running the `finalize` methods of objects * that have been found to be discarded but whose `finalize` * methods have not yet been run. When control returns from the * method call, the virtual machine has made a best effort to * complete all outstanding finalizations. * * The virtual machine performs the finalization process * automatically as needed, in a separate thread, if the * `runFinalization` method is not invoked explicitly. * * The method {@link System#runFinalization()} is the conventional * and convenient means of invoking this method. * * @see java.lang.Object#finalize() */ runFinalization(): void; /** * Loads the native library specified by the filename argument. The filename * argument must be an absolute path name. * (for example * `Runtime.getRuntime().load("/home/avh/lib/libX11.so");`). * * If the filename argument, when stripped of any platform-specific library * prefix, path, and file extension, indicates a library whose name is, * for example, L, and a native library called L is statically linked * with the VM, then the JNI_OnLoad_L function exported by the library * is invoked rather than attempting to load a dynamic library. * A filename matching the argument does not have to exist in the file * system. * See the JNI Specification * for more details. * * Otherwise, the filename argument is mapped to a native library image in * an implementation-dependent manner. * * First, if there is a security manager, its `checkLink` * method is called with the `filename` as its argument. * This may result in a security exception. * * This is similar to the method {@link #loadLibrary(String)}, but it * accepts a general file name as an argument rather than just a library * name, allowing any file of native code to be loaded. * * The method {@link System#load(String)} is the conventional and * convenient means of invoking this method. * * @param filename the file to load. * @throws SecurityException if a security manager exists and its * `checkLink` method doesn't allow * loading of the specified dynamic library * @throws UnsatisfiedLinkError if either the filename is not an * absolute path name, the native library is not statically * linked with the VM, or the library cannot be mapped to * a native library image by the host system. * @throws NullPointerException if `filename` is * `null` * @see java.lang.Runtime#getRuntime() * @see java.lang.SecurityException * @see java.lang.SecurityManager#checkLink(java.lang.String) */ load(filename: string): void; /** * Loads the native library specified by the `libname` * argument. The `libname` argument must not contain any platform * specific prefix, file extension or path. If a native library * called `libname` is statically linked with the VM, then the * JNI_OnLoad_`libname` function exported by the library is invoked. * See the JNI Specification * for more details. * * Otherwise, the libname argument is loaded from a system library * location and mapped to a native library image in an * implementation-dependent manner. * * First, if there is a security manager, its `checkLink` * method is called with the `libname` as its argument. * This may result in a security exception. * * The method {@link System#loadLibrary(String)} is the conventional * and convenient means of invoking this method. If native * methods are to be used in the implementation of a class, a standard * strategy is to put the native code in a library file (call it * `LibFile`) and then to put a static initializer: * * static { System.loadLibrary("LibFile"); } * * within the class declaration. When the class is loaded and * initialized, the necessary native code implementation for the native * methods will then be loaded as well. * * If this method is called more than once with the same library * name, the second and subsequent calls are ignored. * * @param libname the name of the library. * @throws SecurityException if a security manager exists and its * `checkLink` method doesn't allow * loading of the specified dynamic library * @throws UnsatisfiedLinkError if either the libname argument * contains a file path, the native library is not statically * linked with the VM, or the library cannot be mapped to a * native library image by the host system. * @throws NullPointerException if `libname` is * `null` * @see java.lang.SecurityException * @see java.lang.SecurityManager#checkLink(java.lang.String) */ loadLibrary(libname: string): void; /** * Returns the version of the Java Runtime Environment as a {@link Version}. * * @return the {@link Version} of the Java Runtime Environment * * @since 9 */ static version(): Version; } /** * The class `Exception` and its subclasses are a form of * `Throwable` that indicates conditions that a reasonable * application might want to catch. * * The class `Exception` and any subclasses that are not also * subclasses of {@link RuntimeException} are checked * exceptions. Checked exceptions need to be declared in a * method or constructor's `throws` clause if they can be thrown * by the execution of the method or constructor and propagate outside * the method or constructor boundary. * * @author Frank Yellin * @see java.lang.Error * @jls 11.2 Compile-Time Checking of Exceptions * @since 1.0 */ export class Exception extends Throwable { /** * Constructs a new exception with `null` as its detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. */ constructor(); /** * Constructs a new exception with the specified detail message. The * cause is not initialized, and may subsequently be initialized by * a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ constructor(message: string); /** * Constructs a new exception with the specified detail message and * cause. Note that the detail message associated with * `cause` is not automatically incorporated in * this exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ constructor(message: string, cause: Throwable); /** * Constructs a new exception with the specified cause and a detail * message of `(cause==null ? null : cause.toString())` (which * typically contains the class and detail message of `cause`). * This constructor is useful for exceptions that are little more than * wrappers for other throwables (for example, {@link * java.security.PrivilegedActionException}). * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ constructor(cause: Throwable); } export class RuntimePermission extends BasicPermission { constructor(name: string); constructor(name: string, actions: string); } /** * An `Error` is a subclass of `Throwable` * that indicates serious problems that a reasonable application * should not try to catch. Most such errors are abnormal conditions. * The `ThreadDeath` error, though a "normal" condition, * is also a subclass of `Error` because most applications * should not try to catch it. * * A method is not required to declare in its `throws` * clause any subclasses of `Error` that might be thrown * during the execution of the method but not caught, since these * errors are abnormal conditions that should never occur. * * That is, `Error` and its subclasses are regarded as unchecked * exceptions for the purposes of compile-time checking of exceptions. * * @author Frank Yellin * @see java.lang.ThreadDeath * @jls 11.2 Compile-Time Checking of Exceptions * @since 1.0 */ export class Error extends Throwable { /** * Constructs a new error with `null` as its detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. */ constructor(); /** * Constructs a new error with the specified detail message. The * cause is not initialized, and may subsequently be initialized by * a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ constructor(message: string); /** * Constructs a new error with the specified detail message and * cause. Note that the detail message associated with * `cause` is not automatically incorporated in * this error's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ constructor(message: string, cause: Throwable); /** * Constructs a new error with the specified cause and a detail * message of `(cause==null ? null : cause.toString())` (which * typically contains the class and detail message of `cause`). * This constructor is useful for errors that are little more than * wrappers for other throwables. * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ constructor(cause: Throwable); } /** * Thrown to indicate that an assertion has failed. * * The seven one-argument public constructors provided by this * class ensure that the assertion error returned by the invocation: * * new AssertionError(expression) * * has as its detail message the string conversion of * expression (as defined in section {@jls 5.1.11} of * The Java Language Specification), * regardless of the type of expression. * * @since 1.4 */ export class AssertionError extends Error { /** * Constructs an AssertionError with no detail message. */ constructor(); /** * Constructs an AssertionError with its detail message derived * from the specified object, which is converted to a string as * defined in section {@jls 5.1.11} of * The Java Language Specification. * * If the specified object is an instance of `Throwable`, it * becomes the cause of the newly constructed assertion error. * * @param detailMessage value to be used in constructing detail message * @see Throwable#getCause() */ constructor(detailMessage: any); /** * Constructs an AssertionError with its detail message derived * from the specified `boolean`, which is converted to * a string as defined in section {@jls 5.1.11} of * The Java Language Specification. * * @param detailMessage value to be used in constructing detail message */ constructor(detailMessage: boolean); /** * Constructs an AssertionError with its detail message derived * from the specified `char`, which is converted to a * string as defined in section {@jls 5.1.11} of * The Java Language Specification. * * @param detailMessage value to be used in constructing detail message */ constructor(detailMessage: string); /** * Constructs an AssertionError with its detail message derived * from the specified `int`, which is converted to a * string as defined in section {@jls 5.1.11} of * The Java Language Specification. * * @param detailMessage value to be used in constructing detail message */ constructor(detailMessage: number); /** * Constructs a new `AssertionError` with the specified * detail message and cause. * * Note that the detail message associated with * `cause` is not automatically incorporated in * this error's detail message. * * @param message the detail message, may be `null` * @param cause the cause, may be `null` * * @since 1.7 */ constructor(message: string, cause: Throwable); } /** * Thrown to indicate that a thread has attempted to wait on an * object's monitor or to notify other threads waiting on an object's * monitor without owning the specified monitor. * * @see java.lang.Object#notify() * @see java.lang.Object#notifyAll() * @see java.lang.Object#wait() * @see java.lang.Object#wait(long) * @see java.lang.Object#wait(long, int) * @since 1.0 */ export class IllegalMonitorStateException extends RuntimeException { /** * Constructs an `IllegalMonitorStateException` with no * detail message. */ constructor(); /** * Constructs an `IllegalMonitorStateException` with the * specified detail message. * * @param s the detail message. */ constructor(s: string); } /** * A program element annotated `@Deprecated` is one that programmers * are discouraged from using. An element may be deprecated for any of several * reasons, for example, its usage is likely to lead to errors; it may * be changed incompatibly or removed in a future version; it has been * superseded by a newer, usually preferable alternative; or it is obsolete. * * Compilers issue warnings when a deprecated program element is used or * overridden in non-deprecated code. Use of the `@Deprecated` * annotation on a local variable declaration or on a parameter declaration * or a package declaration has no effect on the warnings issued by a compiler. * * When a module is deprecated, the use of that module in ` * requires`, but not in `exports` or `opens` clauses causes * a warning to be issued. A module being deprecated does not cause * warnings to be issued for uses of types within the module. * * This annotation type has a string-valued element `since`. The value * of this element indicates the version in which the annotated program element * was first deprecated. * * This annotation type has a boolean-valued element `forRemoval`. * A value of `true` indicates intent to remove the annotated program * element in a future version. A value of `false` indicates that use of * the annotated program element is discouraged, but at the time the program * element was annotated, there was no specific intent to remove it. * * @apiNote * It is strongly recommended that the reason for deprecating a program element * be explained in the documentation, using the `@deprecated` * javadoc tag. The documentation should also suggest and link to a * recommended replacement API, if applicable. A replacement API often * has subtly different semantics, so such issues should be discussed as * well. * * It is recommended that a `since` value be provided with all newly * annotated program elements. Note that `since` cannot be mandatory, * as there are many existing annotations that lack this element value. * * There is no defined order among annotation elements. As a matter of * style, the `since` element should be placed first. * * The `@Deprecated` annotation should always be present if * the `@deprecated` javadoc tag is present, and vice-versa. * * @author Neal Gafter * @since 1.5 * @jls 9.6.4.6 @Deprecated */ export class Deprecated { } /** * `RuntimeException` is the superclass of those * exceptions that can be thrown during the normal operation of the * Java Virtual Machine. * * `RuntimeException` and its subclasses are unchecked * exceptions. Unchecked exceptions do not need to be * declared in a method or constructor's `throws` clause if they * can be thrown by the execution of the method or constructor and * propagate outside the method or constructor boundary. * * @author Frank Yellin * @jls 11.2 Compile-Time Checking of Exceptions * @since 1.0 */ export class RuntimeException extends Exception { /** Constructs a new runtime exception with `null` as its * detail message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. */ constructor(); /** Constructs a new runtime exception with the specified detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ constructor(message: string); /** * Constructs a new runtime exception with the specified detail message and * cause. Note that the detail message associated with * `cause` is not automatically incorporated in * this runtime exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ constructor(message: string, cause: Throwable); /** Constructs a new runtime exception with the specified cause and a * detail message of `(cause==null ? null : cause.toString())` * (which typically contains the class and detail message of * `cause`). This constructor is useful for runtime exceptions * that are little more than wrappers for other throwables. * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A `null` value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ constructor(cause: Throwable); } /** * Thrown when an application tries to load in a class through its * string name using: * * The `forName` method in class `Class`. * The `findSystemClass` method in class * `ClassLoader` . * The `loadClass` method in class `ClassLoader`. * * * but no definition for the class with the specified name could be found. * * As of release 1.4, this exception has been retrofitted to conform to * the general purpose exception-chaining mechanism. The "optional exception * that was raised while loading the class" that may be provided at * construction time and accessed via the {@link #getException()} method is * now known as the cause, and may be accessed via the {@link * Throwable#getCause()} method, as well as the aforementioned "legacy method." * * @see java.lang.Class#forName(java.lang.String) * @see java.lang.ClassLoader#findSystemClass(java.lang.String) * @see java.lang.ClassLoader#loadClass(java.lang.String, boolean) * @since 1.0 */ export class ClassNotFoundException extends ReflectiveOperationException { /** * Constructs a `ClassNotFoundException` with no detail message. */ constructor(); /** * Constructs a `ClassNotFoundException` with the * specified detail message. * * @param s the detail message. */ constructor(s: string); /** * Constructs a `ClassNotFoundException` with the * specified detail message and optional exception that was * raised while loading the class. * * @param s the detail message * @param ex the exception that was raised while loading the class * @since 1.2 */ constructor(s: string, ex: Throwable); /** * Returns the exception that was raised if an error occurred while * attempting to load the class. Otherwise, returns `null`. * * This method predates the general-purpose exception chaining facility. * The {@link Throwable#getCause()} method is now the preferred means of * obtaining this information. * * @return the `Exception` that was raised while loading a class * @since 1.2 */ get exception(): Throwable; } /** * Signals that an unexpected exception has occurred in a static initializer. * An `ExceptionInInitializerError` is thrown to indicate that an * exception occurred during evaluation of a static initializer or the * initializer for a static variable. * * As of release 1.4, this exception has been retrofitted to conform to * the general purpose exception-chaining mechanism. The "saved throwable * object" that may be provided at construction time and accessed via * the {@link #getException()} method is now known as the cause, * and may be accessed via the {@link Throwable#getCause()} method, as well * as the aforementioned "legacy method." * * @author Frank Yellin * @since 1.1 */ export class ExceptionInInitializerError extends LinkageError { /** * Constructs an `ExceptionInInitializerError` with * `null` as its detail message string and with no saved * throwable object. * A detail message is a String that describes this particular exception. */ constructor(); /** * Constructs a new `ExceptionInInitializerError` class by * saving a reference to the `Throwable` object thrown for * later retrieval by the {@link #getException()} method. The detail * message string is set to `null`. * * @param thrown The exception thrown */ constructor(thrown: Throwable); /** * Constructs an `ExceptionInInitializerError` with the specified detail * message string. A detail message is a String that describes this * particular exception. The detail message string is saved for later * retrieval by the {@link Throwable#getMessage()} method. There is no * saved throwable object. * * @param s the detail message */ constructor(s: string); /** * Returns the exception that occurred during a static initialization that * caused this error to be created. * * This method predates the general-purpose exception chaining facility. * The {@link Throwable#getCause()} method is now the preferred means of * obtaining this information. * * @return the saved throwable object of this * `ExceptionInInitializerError`, or `null` * if this `ExceptionInInitializerError` has no saved * throwable object. */ get exception(): Throwable; } /** * Thrown when a particular method cannot be found. * * @since 1.0 */ export class NoSuchMethodException extends ReflectiveOperationException { /** * Constructs a `NoSuchMethodException` without a detail message. */ constructor(); /** * Constructs a `NoSuchMethodException` with a detail message. * * @param s the detail message. */ constructor(s: string); } /** * Thrown when an application attempts to use `null` in a * case where an object is required. These include: * * Calling the instance method of a `null` object. * Accessing or modifying the field of a `null` object. * Taking the length of `null` as if it were an array. * Accessing or modifying the slots of `null` as if it * were an array. * Throwing `null` as if it were a `Throwable` * value. * * * Applications should throw instances of this class to indicate * other illegal uses of the `null` object. * * `NullPointerException` objects may be constructed by the * virtual machine as if {@linkplain Throwable#Throwable(String, * Throwable, boolean, boolean) suppression were disabled and/or the * stack trace was not writable}. * * @since 1.0 */ export class NullPointerException extends RuntimeException { /** * Constructs a `NullPointerException` with no detail message. */ constructor(); /** * Constructs a `NullPointerException` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); /** * {@inheritDoc} */ fillInStackTrace(): Throwable; /** * Returns the detail message string of this throwable. * * If a non-null message was supplied in a constructor it is * returned. Otherwise, an implementation specific message or * `null` is returned. * * @implNote * If no explicit message was passed to the constructor, and as * long as certain internal information is available, a verbose * description of the null reference is returned. * The internal information is not available in deserialized * NullPointerExceptions. * * @return the detail message string, which may be `null`. */ get message(): string; } /** * Thrown to indicate that a method has been called by an inappropriate caller. * * @since 9 * @see StackWalker#getCallerClass */ export class IllegalCallerException extends RuntimeException { /** * Constructs an IllegalCallerException with no detail message. */ constructor(); /** * Constructs an IllegalCallerException with the specified detail * message. * * @param s the String that contains a detailed message (can be null) */ constructor(s: string); /** * Constructs a new exception with the specified detail message and * cause. * * @param message the detail message (can be null) * @param cause the cause (can be null) */ constructor(message: string, cause: Throwable); /** * Constructs a new exception with the specified cause and a detail * message of `(cause==null ? null : cause.toString())` (which * typically contains the class and detail message of `cause`). * * @param cause the cause (can be null) */ constructor(cause: Throwable); } /** * Implementing this interface allows an object to be the target of the enhanced * `for` statement (sometimes called the "for-each loop" statement). * * @param the type of elements returned by the iterator * * @since 1.5 * @jls 14.14.2 The enhanced `for` statement */ export class Iterable { [Symbol.iterator](): globalThis.Iterator; /** * Returns an iterator over elements of type `T`. * * @return an Iterator. */ iterator(): Iterator; /** * Performs the given action for each element of the `Iterable` * until all elements have been processed or the action throws an * exception. Actions are performed in the order of iteration, if that * order is specified. Exceptions thrown by the action are relayed to the * caller. * * The behavior of this method is unspecified if the action performs * side-effects that modify the underlying source of elements, unless an * overriding class has specified a concurrent modification policy. * * @implSpec * The default implementation behaves as if: * {@code * for (T t : this) * action.accept(t); * } * * @param action The action to be performed for each element * @throws NullPointerException if the specified action is null * @since 1.8 */ forEach(action: Consumer): void; /** * Creates a {@link Spliterator} over the elements described by this * `Iterable`. * * @implSpec * The default implementation creates an * early-binding * spliterator from the iterable's `Iterator`. The spliterator * inherits the fail-fast properties of the iterable's iterator. * * @implNote * The default implementation should usually be overridden. The * spliterator returned by the default implementation has poor splitting * capabilities, is unsized, and does not report any spliterator * characteristics. Implementing classes can nearly always provide a * better implementation. * * @return a `Spliterator` over the elements described by this * `Iterable`. * @since 1.8 */ spliterator(): Spliterator; } /** * Thrown if the Java Virtual Machine or a `ClassLoader` instance * tries to load in the definition of a class (as part of a normal method call * or as part of creating a new instance using the `new` expression) * and no definition of the class could be found. * * The searched-for class definition existed when the currently * executing class was compiled, but the definition can no longer be * found. * * @since 1.0 */ export class NoClassDefFoundError extends LinkageError { /** * Constructs a `NoClassDefFoundError` with no detail message. */ constructor(); /** * Constructs a `NoClassDefFoundError` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); } /** * The security manager is a class that allows * applications to implement a security policy. It allows an * application to determine, before performing a possibly unsafe or * sensitive operation, what the operation is and whether * it is being attempted in a security context that allows the * operation to be performed. The * application can allow or disallow the operation. * * The `SecurityManager` class contains many methods with * names that begin with the word `check`. These methods * are called by various methods in the Java libraries before those * methods perform certain potentially sensitive operations. The * invocation of such a `check` method typically looks like this: * * SecurityManager security = System.getSecurityManager(); * if (security != null) { * security.checkXXX(argument,  . . . ); * } * * * The security manager is thereby given an opportunity to prevent * completion of the operation by throwing an exception. A security * manager routine simply returns if the operation is permitted, but * throws a `SecurityException` if the operation is not * permitted. * * Environments using a security manager will typically set the security * manager at startup. In the JDK implementation, this is done by setting * the system property `java.security.manager` on the command line to * the class name of the security manager. It can also be set to the empty * String ("") or the special token "`default`" to use the * default `java.lang.SecurityManager`. If a class name is specified, * it must be `java.lang.SecurityManager` or a public subclass and have * a public no-arg constructor. The class is loaded by the * {@linkplain ClassLoader#getSystemClassLoader() built-in system class loader} * if it is not `java.lang.SecurityManager`. If the * `java.security.manager` system property is not set, the default value * is `null`, which means a security manager will not be set at startup. * * The Java run-time may also allow, but is not required to allow, the security * manager to be set dynamically by invoking the * {@link System#setSecurityManager(SecurityManager) setSecurityManager} method. * In the JDK implementation, if the Java virtual machine is started with * the `java.security.manager` system property set to the special token * "`disallow`" then a security manager will not be set at startup and * cannot be set dynamically (the * {@link System#setSecurityManager(SecurityManager) setSecurityManager} * method will throw an `UnsupportedOperationException`). If the * `java.security.manager` system property is not set or is set to the * special token "`allow`", then a security manager will not be set at * startup but can be set dynamically. Finally, if the * `java.security.manager` system property is set to the class name of * the security manager, or to the empty String ("") or the special token * "`default`", then a security manager is set at startup (as described * previously) and can also be subsequently replaced (or disabled) dynamically * (subject to the policy of the currently installed security manager). The * following table illustrates the behavior of the JDK implementation for the * different settings of the `java.security.manager` system property: * * property value, * the SecurityManager set at startup, * can dynamically set a SecurityManager * * * * Property Value * The SecurityManager set at startup * System.setSecurityManager run-time behavior * * * * * * null * None * Success or throws `SecurityException` if not permitted by * the currently installed security manager * * * * empty String ("") * `java.lang.SecurityManager` * Success or throws `SecurityException` if not permitted by * the currently installed security manager * * * * "default" * `java.lang.SecurityManager` * Success or throws `SecurityException` if not permitted by * the currently installed security manager * * * * "disallow" * None * Always throws `UnsupportedOperationException` * * * * "allow" * None * Success or throws `SecurityException` if not permitted by * the currently installed security manager * * * * a class name * the named class * Success or throws `SecurityException` if not permitted by * the currently installed security manager * * * * * A future release of the JDK may change the default value of the * `java.security.manager` system property to "`disallow`". * * The current security manager is returned by the * {@link System#getSecurityManager() getSecurityManager} method. * * The special method * {@link SecurityManager#checkPermission(java.security.Permission)} * determines whether an access request indicated by a specified * permission should be granted or denied. The * default implementation calls * * * AccessController.checkPermission(perm); * * * * If a requested access is allowed, * `checkPermission` returns quietly. If denied, a * `SecurityException` is thrown. * * The default implementation of each of the other * `check` methods in `SecurityManager` is to * call the `SecurityManager checkPermission` method * to determine if the calling thread has permission to perform the requested * operation. * * Note that the `checkPermission` method with * just a single permission argument always performs security checks * within the context of the currently executing thread. * Sometimes a security check that should be made within a given context * will actually need to be done from within a * different context (for example, from within a worker thread). * The {@link SecurityManager#getSecurityContext getSecurityContext} method * and the {@link SecurityManager#checkPermission(java.security.Permission, * java.lang.Object) checkPermission} * method that includes a context argument are provided * for this situation. The * `getSecurityContext` method returns a "snapshot" * of the current calling context. (The default implementation * returns an AccessControlContext object.) A sample call is * the following: * * * Object context = null; * SecurityManager sm = System.getSecurityManager(); * if (sm != null) context = sm.getSecurityContext(); * * * * The `checkPermission` method * that takes a context object in addition to a permission * makes access decisions based on that context, * rather than on that of the current execution thread. * Code within a different context can thus call that method, * passing the permission and the * previously-saved context object. A sample call, using the * SecurityManager `sm` obtained as in the previous example, * is the following: * * * if (sm != null) sm.checkPermission(permission, context); * * * Permissions fall into these categories: File, Socket, Net, * Security, Runtime, Property, AWT, Reflect, and Serializable. * The classes managing these various * permission categories are `java.io.FilePermission`, * `java.net.SocketPermission`, * `java.net.NetPermission`, * `java.security.SecurityPermission`, * `java.lang.RuntimePermission`, * `java.util.PropertyPermission`, * `java.awt.AWTPermission`, * `java.lang.reflect.ReflectPermission`, and * `java.io.SerializablePermission`. * * All but the first two (FilePermission and SocketPermission) are * subclasses of `java.security.BasicPermission`, which itself * is an abstract subclass of the * top-level class for permissions, which is * `java.security.Permission`. BasicPermission defines the * functionality needed for all permissions that contain a name * that follows the hierarchical property naming convention * (for example, "exitVM", "setFactory", "queuePrintJob", etc). * An asterisk * may appear at the end of the name, following a ".", or by itself, to * signify a wildcard match. For example: "a.*" or "*" is valid, * "*a" or "a*b" is not valid. * * FilePermission and SocketPermission are subclasses of the * top-level class for permissions * (`java.security.Permission`). Classes like these * that have a more complicated name syntax than that used by * BasicPermission subclass directly from Permission rather than from * BasicPermission. For example, * for a `java.io.FilePermission` object, the permission name is * the path name of a file (or directory). * * Some of the permission classes have an "actions" list that tells * the actions that are permitted for the object. For example, * for a `java.io.FilePermission` object, the actions list * (such as "read, write") specifies which actions are granted for the * specified file (or for files in the specified directory). * * Other permission classes are for "named" permissions - * ones that contain a name but no actions list; you either have the * named permission or you don't. * * Note: There is also a `java.security.AllPermission` * permission that implies all permissions. It exists to simplify the work * of system administrators who might need to perform multiple * tasks that require all (or numerous) permissions. * * See {@extLink security_guide_permissions * Permissions in the Java Development Kit (JDK)} * for permission-related information. * This document includes a table listing the various SecurityManager * `check` methods and the permission(s) the default * implementation of each such method requires. * It also contains a table of the methods * that require permissions, and for each such method tells * which permission it requires. * * @author Arthur van Hoff * @author Roland Schemers * * @see java.lang.ClassLoader * @see java.lang.SecurityException * @see java.lang.System#getSecurityManager() getSecurityManager * @see java.lang.System#setSecurityManager(java.lang.SecurityManager) * setSecurityManager * @see java.security.AccessController AccessController * @see java.security.AccessControlContext AccessControlContext * @see java.security.AccessControlException AccessControlException * @see java.security.Permission * @see java.security.BasicPermission * @see java.io.FilePermission * @see java.net.SocketPermission * @see java.util.PropertyPermission * @see java.lang.RuntimePermission * @see java.security.Policy Policy * @see java.security.SecurityPermission SecurityPermission * @see java.security.ProtectionDomain * * @since 1.0 */ export class SecurityManager { /** * Constructs a new `SecurityManager`. * * If there is a security manager already installed, this method first * calls the security manager's `checkPermission` method * with the `RuntimePermission("createSecurityManager")` * permission to ensure the calling thread has permission to create a new * security manager. * This may result in throwing a `SecurityException`. * * @throws java.lang.SecurityException if a security manager already * exists and its `checkPermission` method * doesn't allow creation of a new security manager. * @see java.lang.System#getSecurityManager() * @see #checkPermission(java.security.Permission) checkPermission * @see java.lang.RuntimePermission */ constructor(); /** * Creates an object that encapsulates the current execution * environment. The result of this method is used, for example, by the * three-argument `checkConnect` method and by the * two-argument `checkRead` method. * These methods are needed because a trusted method may be called * on to read a file or open a socket on behalf of another method. * The trusted method needs to determine if the other (possibly * untrusted) method would be allowed to perform the operation on its * own. * The default implementation of this method is to return * an `AccessControlContext` object. * * @return an implementation-dependent object that encapsulates * sufficient information about the current execution environment * to perform some security checks later. * @see java.lang.SecurityManager#checkConnect(java.lang.String, int, * java.lang.Object) checkConnect * @see java.lang.SecurityManager#checkRead(java.lang.String, * java.lang.Object) checkRead * @see java.security.AccessControlContext AccessControlContext */ get securityContext(): any; /** * Throws a `SecurityException` if the requested * access, specified by the given permission, is not permitted based * on the security policy currently in effect. * * This method calls `AccessController.checkPermission` * with the given permission. * * @param perm the requested permission. * @throws SecurityException if access is not permitted based on * the current security policy. * @throws NullPointerException if the permission argument is * `null`. * @since 1.2 */ checkPermission(perm: Permission): void; /** * Throws a `SecurityException` if the * specified security context is denied access to the resource * specified by the given permission. * The context must be a security * context returned by a previous call to * `getSecurityContext` and the access control * decision is based upon the configured security policy for * that security context. * * If `context` is an instance of * `AccessControlContext` then the * `AccessControlContext.checkPermission` method is * invoked with the specified permission. * * If `context` is not an instance of * `AccessControlContext` then a * `SecurityException` is thrown. * * @param perm the specified permission * @param context a system-dependent security context. * @throws SecurityException if the specified security context * is not an instance of `AccessControlContext` * (e.g., is `null`), or is denied access to the * resource specified by the given permission. * @throws NullPointerException if the permission argument is * `null`. * @see java.lang.SecurityManager#getSecurityContext() * @see java.security.AccessControlContext#checkPermission(java.security.Permission) * @since 1.2 */ checkPermission(perm: Permission, context: any): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to create a new class loader. * * This method calls `checkPermission` with the * `RuntimePermission("createClassLoader")` * permission. * * If you override this method, then you should make a call to * `super.checkCreateClassLoader` * at the point the overridden method would normally throw an * exception. * * @throws SecurityException if the calling thread does not * have permission * to create a new class loader. * @see java.lang.ClassLoader#ClassLoader() * @see #checkPermission(java.security.Permission) checkPermission */ checkCreateClassLoader(): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to modify the thread argument. * * This method is invoked for the current security manager by the * `stop`, `suspend`, `resume`, * `setPriority`, `setName`, and * `setDaemon` methods of class `Thread`. * * If the thread argument is a system thread (belongs to * the thread group with a `null` parent) then * this method calls `checkPermission` with the * `RuntimePermission("modifyThread")` permission. * If the thread argument is not a system thread, * this method just returns silently. * * Applications that want a stricter policy should override this * method. If this method is overridden, the method that overrides * it should additionally check to see if the calling thread has the * `RuntimePermission("modifyThread")` permission, and * if so, return silently. This is to ensure that code granted * that permission (such as the JDK itself) is allowed to * manipulate any thread. * * If this method is overridden, then * `super.checkAccess` should * be called by the first statement in the overridden method, or the * equivalent security check should be placed in the overridden method. * * @param t the thread to be checked. * @throws SecurityException if the calling thread does not have * permission to modify the thread. * @throws NullPointerException if the thread argument is * `null`. * @see java.lang.Thread#resume() resume * @see java.lang.Thread#setDaemon(boolean) setDaemon * @see java.lang.Thread#setName(java.lang.String) setName * @see java.lang.Thread#setPriority(int) setPriority * @see java.lang.Thread#stop() stop * @see java.lang.Thread#suspend() suspend * @see #checkPermission(java.security.Permission) checkPermission */ checkAccess(t: Thread): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to modify the thread group argument. * * This method is invoked for the current security manager when a * new child thread or child thread group is created, and by the * `setDaemon`, `setMaxPriority`, * `stop`, `suspend`, `resume`, and * `destroy` methods of class `ThreadGroup`. * * If the thread group argument is the system thread group ( * has a `null` parent) then * this method calls `checkPermission` with the * `RuntimePermission("modifyThreadGroup")` permission. * If the thread group argument is not the system thread group, * this method just returns silently. * * Applications that want a stricter policy should override this * method. If this method is overridden, the method that overrides * it should additionally check to see if the calling thread has the * `RuntimePermission("modifyThreadGroup")` permission, and * if so, return silently. This is to ensure that code granted * that permission (such as the JDK itself) is allowed to * manipulate any thread. * * If this method is overridden, then * `super.checkAccess` should * be called by the first statement in the overridden method, or the * equivalent security check should be placed in the overridden method. * * @param g the thread group to be checked. * @throws SecurityException if the calling thread does not have * permission to modify the thread group. * @throws NullPointerException if the thread group argument is * `null`. * @see java.lang.ThreadGroup#destroy() destroy * @see java.lang.ThreadGroup#resume() resume * @see java.lang.ThreadGroup#setDaemon(boolean) setDaemon * @see java.lang.ThreadGroup#setMaxPriority(int) setMaxPriority * @see java.lang.ThreadGroup#stop() stop * @see java.lang.ThreadGroup#suspend() suspend * @see #checkPermission(java.security.Permission) checkPermission */ checkAccess(g: ThreadGroup): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to cause the Java Virtual Machine to * halt with the specified status code. * * This method is invoked for the current security manager by the * `exit` method of class `Runtime`. A status * of `0` indicates success; other values indicate various * errors. * * This method calls `checkPermission` with the * `RuntimePermission("exitVM."+status)` permission. * * If you override this method, then you should make a call to * `super.checkExit` * at the point the overridden method would normally throw an * exception. * * @param status the exit status. * @throws SecurityException if the calling thread does not have * permission to halt the Java Virtual Machine with * the specified status. * @see java.lang.Runtime#exit(int) exit * @see #checkPermission(java.security.Permission) checkPermission */ checkExit(status: number): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to create a subprocess. * * This method is invoked for the current security manager by the * `exec` methods of class `Runtime`. * * This method calls `checkPermission` with the * `FilePermission(cmd,"execute")` permission * if cmd is an absolute path, otherwise it calls * `checkPermission` with * FilePermission("<>","execute"). * * If you override this method, then you should make a call to * `super.checkExec` * at the point the overridden method would normally throw an * exception. * * @param cmd the specified system command. * @throws SecurityException if the calling thread does not have * permission to create a subprocess. * @throws NullPointerException if the `cmd` argument is * `null`. * @see java.lang.Runtime#exec(java.lang.String) * @see java.lang.Runtime#exec(java.lang.String, java.lang.String[]) * @see java.lang.Runtime#exec(java.lang.String[]) * @see java.lang.Runtime#exec(java.lang.String[], java.lang.String[]) * @see #checkPermission(java.security.Permission) checkPermission */ checkExec(cmd: string): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to dynamic link the library code * specified by the string argument file. The argument is either a * simple library name or a complete filename. * * This method is invoked for the current security manager by * methods `load` and `loadLibrary` of class * `Runtime`. * * This method calls `checkPermission` with the * `RuntimePermission("loadLibrary."+lib)` permission. * * If you override this method, then you should make a call to * `super.checkLink` * at the point the overridden method would normally throw an * exception. * * @param lib the name of the library. * @throws SecurityException if the calling thread does not have * permission to dynamically link the library. * @throws NullPointerException if the `lib` argument is * `null`. * @see java.lang.Runtime#load(java.lang.String) * @see java.lang.Runtime#loadLibrary(java.lang.String) * @see #checkPermission(java.security.Permission) checkPermission */ checkLink(lib: string): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to read from the specified file * descriptor. * * This method calls `checkPermission` with the * `RuntimePermission("readFileDescriptor")` * permission. * * If you override this method, then you should make a call to * `super.checkRead` * at the point the overridden method would normally throw an * exception. * * @param fd the system-dependent file descriptor. * @throws SecurityException if the calling thread does not have * permission to access the specified file descriptor. * @throws NullPointerException if the file descriptor argument is * `null`. * @see java.io.FileDescriptor * @see #checkPermission(java.security.Permission) checkPermission */ checkRead(fd: FileDescriptor): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to read the file specified by the * string argument. * * This method calls `checkPermission` with the * `FilePermission(file,"read")` permission. * * If you override this method, then you should make a call to * `super.checkRead` * at the point the overridden method would normally throw an * exception. * * @param file the system-dependent file name. * @throws SecurityException if the calling thread does not have * permission to access the specified file. * @throws NullPointerException if the `file` argument is * `null`. * @see #checkPermission(java.security.Permission) checkPermission */ checkRead(file: string): void; /** * Throws a `SecurityException` if the * specified security context is not allowed to read the file * specified by the string argument. The context must be a security * context returned by a previous call to * `getSecurityContext`. * If `context` is an instance of * `AccessControlContext` then the * `AccessControlContext.checkPermission` method will * be invoked with the `FilePermission(file,"read")` permission. * If `context` is not an instance of * `AccessControlContext` then a * `SecurityException` is thrown. * * If you override this method, then you should make a call to * `super.checkRead` * at the point the overridden method would normally throw an * exception. * * @param file the system-dependent filename. * @param context a system-dependent security context. * @throws SecurityException if the specified security context * is not an instance of `AccessControlContext` * (e.g., is `null`), or does not have permission * to read the specified file. * @throws NullPointerException if the `file` argument is * `null`. * @see java.lang.SecurityManager#getSecurityContext() * @see java.security.AccessControlContext#checkPermission(java.security.Permission) */ checkRead(file: string, context: any): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to write to the specified file * descriptor. * * This method calls `checkPermission` with the * `RuntimePermission("writeFileDescriptor")` * permission. * * If you override this method, then you should make a call to * `super.checkWrite` * at the point the overridden method would normally throw an * exception. * * @param fd the system-dependent file descriptor. * @throws SecurityException if the calling thread does not have * permission to access the specified file descriptor. * @throws NullPointerException if the file descriptor argument is * `null`. * @see java.io.FileDescriptor * @see #checkPermission(java.security.Permission) checkPermission */ checkWrite(fd: FileDescriptor): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to write to the file specified by * the string argument. * * This method calls `checkPermission` with the * `FilePermission(file,"write")` permission. * * If you override this method, then you should make a call to * `super.checkWrite` * at the point the overridden method would normally throw an * exception. * * @param file the system-dependent filename. * @throws SecurityException if the calling thread does not * have permission to access the specified file. * @throws NullPointerException if the `file` argument is * `null`. * @see #checkPermission(java.security.Permission) checkPermission */ checkWrite(file: string): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to delete the specified file. * * This method is invoked for the current security manager by the * `delete` method of class `File`. * * This method calls `checkPermission` with the * `FilePermission(file,"delete")` permission. * * If you override this method, then you should make a call to * `super.checkDelete` * at the point the overridden method would normally throw an * exception. * * @param file the system-dependent filename. * @throws SecurityException if the calling thread does not * have permission to delete the file. * @throws NullPointerException if the `file` argument is * `null`. * @see java.io.File#delete() * @see #checkPermission(java.security.Permission) checkPermission */ checkDelete(file: string): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to open a socket connection to the * specified host and port number. * * A port number of `-1` indicates that the calling * method is attempting to determine the IP address of the specified * host name. * * This method calls `checkPermission` with the * `SocketPermission(host+":"+port,"connect")` permission if * the port is not equal to -1. If the port is equal to -1, then * it calls `checkPermission` with the * `SocketPermission(host,"resolve")` permission. * * If you override this method, then you should make a call to * `super.checkConnect` * at the point the overridden method would normally throw an * exception. * * @param host the host name port to connect to. * @param port the protocol port to connect to. * @throws SecurityException if the calling thread does not have * permission to open a socket connection to the specified * `host` and `port`. * @throws NullPointerException if the `host` argument is * `null`. * @see #checkPermission(java.security.Permission) checkPermission */ checkConnect(host: string, port: number): void; /** * Throws a `SecurityException` if the * specified security context is not allowed to open a socket * connection to the specified host and port number. * * A port number of `-1` indicates that the calling * method is attempting to determine the IP address of the specified * host name. * If `context` is not an instance of * `AccessControlContext` then a * `SecurityException` is thrown. * * Otherwise, the port number is checked. If it is not equal * to -1, the `context`'s `checkPermission` * method is called with a * `SocketPermission(host+":"+port,"connect")` permission. * If the port is equal to -1, then * the `context`'s `checkPermission` method * is called with a * `SocketPermission(host,"resolve")` permission. * * If you override this method, then you should make a call to * `super.checkConnect` * at the point the overridden method would normally throw an * exception. * * @param host the host name port to connect to. * @param port the protocol port to connect to. * @param context a system-dependent security context. * @throws SecurityException if the specified security context * is not an instance of `AccessControlContext` * (e.g., is `null`), or does not have permission * to open a socket connection to the specified * `host` and `port`. * @throws NullPointerException if the `host` argument is * `null`. * @see java.lang.SecurityManager#getSecurityContext() * @see java.security.AccessControlContext#checkPermission(java.security.Permission) */ checkConnect(host: string, port: number, context: any): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to wait for a connection request on * the specified local port number. * * This method calls `checkPermission` with the * `SocketPermission("localhost:"+port,"listen")`. * * If you override this method, then you should make a call to * `super.checkListen` * at the point the overridden method would normally throw an * exception. * * @param port the local port. * @throws SecurityException if the calling thread does not have * permission to listen on the specified port. * @see #checkPermission(java.security.Permission) checkPermission */ checkListen(port: number): void; /** * Throws a `SecurityException` if the * calling thread is not permitted to accept a socket connection from * the specified host and port number. * * This method is invoked for the current security manager by the * `accept` method of class `ServerSocket`. * * This method calls `checkPermission` with the * `SocketPermission(host+":"+port,"accept")` permission. * * If you override this method, then you should make a call to * `super.checkAccept` * at the point the overridden method would normally throw an * exception. * * @param host the host name of the socket connection. * @param port the port number of the socket connection. * @throws SecurityException if the calling thread does not have * permission to accept the connection. * @throws NullPointerException if the `host` argument is * `null`. * @see java.net.ServerSocket#accept() * @see #checkPermission(java.security.Permission) checkPermission */ checkAccept(host: string, port: number): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to use * (join/leave/send/receive) IP multicast. * * This method calls `checkPermission` with the * java.net.SocketPermission(maddr.getHostAddress(), * "accept,connect") permission. * * If you override this method, then you should make a call to * `super.checkMulticast` * at the point the overridden method would normally throw an * exception. * * @param maddr Internet group address to be used. * @throws SecurityException if the calling thread is not allowed to * use (join/leave/send/receive) IP multicast. * @throws NullPointerException if the address argument is * `null`. * @since 1.1 * @see #checkPermission(java.security.Permission) checkPermission */ checkMulticast(maddr: InetAddress): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to use * (join/leave/send/receive) IP multicast. * * This method calls `checkPermission` with the * java.net.SocketPermission(maddr.getHostAddress(), * "accept,connect") permission. * * If you override this method, then you should make a call to * `super.checkMulticast` * at the point the overridden method would normally throw an * exception. * * @param maddr Internet group address to be used. * @param ttl value in use, if it is multicast send. * Note: this particular implementation does not use the ttl * parameter. * @throws SecurityException if the calling thread is not allowed to * use (join/leave/send/receive) IP multicast. * @throws NullPointerException if the address argument is * `null`. * @since 1.1 * @deprecated Use #checkPermission(java.security.Permission) instead * @see #checkPermission(java.security.Permission) checkPermission */ checkMulticast(maddr: InetAddress, ttl: number): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to access or modify the system * properties. * * This method is used by the `getProperties` and * `setProperties` methods of class `System`. * * This method calls `checkPermission` with the * `PropertyPermission("*", "read,write")` permission. * * If you override this method, then you should make a call to * `super.checkPropertiesAccess` * at the point the overridden method would normally throw an * exception. * * @throws SecurityException if the calling thread does not have * permission to access or modify the system properties. * @see java.lang.System#getProperties() * @see java.lang.System#setProperties(java.util.Properties) * @see #checkPermission(java.security.Permission) checkPermission */ checkPropertiesAccess(): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to access the system property with * the specified `key` name. * * This method is used by the `getProperty` method of * class `System`. * * This method calls `checkPermission` with the * `PropertyPermission(key, "read")` permission. * * If you override this method, then you should make a call to * `super.checkPropertyAccess` * at the point the overridden method would normally throw an * exception. * * @param key a system property key. * * @throws SecurityException if the calling thread does not have * permission to access the specified system property. * @throws NullPointerException if the `key` argument is * `null`. * @throws IllegalArgumentException if `key` is empty. * * @see java.lang.System#getProperty(java.lang.String) * @see #checkPermission(java.security.Permission) checkPermission */ checkPropertyAccess(key: string): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to initiate a print job request. * * This method calls * `checkPermission` with the * `RuntimePermission("queuePrintJob")` permission. * * If you override this method, then you should make a call to * `super.checkPrintJobAccess` * at the point the overridden method would normally throw an * exception. * * @throws SecurityException if the calling thread does not have * permission to initiate a print job request. * @since 1.1 * @see #checkPermission(java.security.Permission) checkPermission */ checkPrintJobAccess(): void; /** * Throws a `SecurityException` if the calling thread is not allowed * to access the specified package. * * During class loading, this method may be called by the `loadClass` * method of class loaders and by the Java Virtual Machine to ensure that * the caller is allowed to access the package of the class that is * being loaded. * * This method checks if the specified package starts with or equals * any of the packages in the `package.access` Security Property. * An implementation may also check the package against an additional * list of restricted packages as noted below. If the package is restricted, * {@link #checkPermission(Permission)} is called with a * `RuntimePermission("accessClassInPackage."+pkg)` permission. * * If this method is overridden, then `super.checkPackageAccess` * should be called as the first line in the overridden method. * * @implNote * This implementation also restricts all non-exported packages of modules * loaded by {@linkplain ClassLoader#getPlatformClassLoader * the platform class loader} or its ancestors. A "non-exported package" * refers to a package that is not exported to all modules. Specifically, * it refers to a package that either is not exported at all by its * containing module or is exported in a qualified fashion by its * containing module. * * @param pkg the package name. * @throws SecurityException if the calling thread does not have * permission to access the specified package. * @throws NullPointerException if the package name argument is * `null`. * @see java.lang.ClassLoader#loadClass(String, boolean) loadClass * @see java.security.Security#getProperty getProperty * @see #checkPermission(Permission) checkPermission */ checkPackageAccess(pkg: string): void; /** * Throws a `SecurityException` if the calling thread is not * allowed to define classes in the specified package. * * This method is called by the `loadClass` method of some * class loaders. * * This method checks if the specified package starts with or equals * any of the packages in the `package.definition` Security * Property. An implementation may also check the package against an * additional list of restricted packages as noted below. If the package * is restricted, {@link #checkPermission(Permission)} is called with a * `RuntimePermission("defineClassInPackage."+pkg)` permission. * * If this method is overridden, then `super.checkPackageDefinition` * should be called as the first line in the overridden method. * * @implNote * This implementation also restricts all non-exported packages of modules * loaded by {@linkplain ClassLoader#getPlatformClassLoader * the platform class loader} or its ancestors. A "non-exported package" * refers to a package that is not exported to all modules. Specifically, * it refers to a package that either is not exported at all by its * containing module or is exported in a qualified fashion by its * containing module. * * @param pkg the package name. * @throws SecurityException if the calling thread does not have * permission to define classes in the specified package. * @throws NullPointerException if the package name argument is * `null`. * @see java.lang.ClassLoader#loadClass(String, boolean) * @see java.security.Security#getProperty getProperty * @see #checkPermission(Permission) checkPermission */ checkPackageDefinition(pkg: string): void; /** * Throws a `SecurityException` if the * calling thread is not allowed to set the socket factory used by * `ServerSocket` or `Socket`, or the stream * handler factory used by `URL`. * * This method calls `checkPermission` with the * `RuntimePermission("setFactory")` permission. * * If you override this method, then you should make a call to * `super.checkSetFactory` * at the point the overridden method would normally throw an * exception. * * @throws SecurityException if the calling thread does not have * permission to specify a socket factory or a stream * handler factory. * * @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory) setSocketFactory * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory) setSocketImplFactory * @see java.net.URL#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory) setURLStreamHandlerFactory * @see #checkPermission(java.security.Permission) checkPermission */ checkSetFactory(): void; /** * Determines whether the permission with the specified permission target * name should be granted or denied. * * If the requested permission is allowed, this method returns * quietly. If denied, a SecurityException is raised. * * This method creates a `SecurityPermission` object for * the given permission target name and calls `checkPermission` * with it. * * See the documentation for * {@link java.security.SecurityPermission} for * a list of possible permission target names. * * If you override this method, then you should make a call to * `super.checkSecurityAccess` * at the point the overridden method would normally throw an * exception. * * @param target the target name of the `SecurityPermission`. * * @throws SecurityException if the calling thread does not have * permission for the requested access. * @throws NullPointerException if `target` is null. * @throws IllegalArgumentException if `target` is empty. * * @since 1.1 * @see #checkPermission(java.security.Permission) checkPermission */ checkSecurityAccess(target: string): void; /** * Returns the thread group into which to instantiate any new * thread being created at the time this is being called. * By default, it returns the thread group of the current * thread. This should be overridden by a specific security * manager to return the appropriate thread group. * * @return ThreadGroup that new threads are instantiated into * @since 1.1 * @see java.lang.ThreadGroup */ get threadGroup(): ThreadGroup; } export class InstantiationError extends IncompatibleClassChangeError { /** * Constructs an `InstantiationError` with no detail message. */ constructor(); /** * Constructs an `InstantiationError` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); } /** * Lazily associate a computed value with (potentially) every type. * For example, if a dynamic language needs to construct a message dispatch * table for each class encountered at a message send call site, * it can use a `ClassValue` to cache information needed to * perform the message send quickly, for each class encountered. * @author John Rose, JSR 292 EG * @since 1.7 */ export class ClassValue { /** * Returns the value for the given class. * If no value has yet been computed, it is obtained by * an invocation of the {@link #computeValue computeValue} method. * * The actual installation of the value on the class * is performed atomically. * At that point, if several racing threads have * computed values, one is chosen, and returned to * all the racing threads. * * The `type` parameter is typically a class, but it may be any type, * such as an interface, a primitive type (like `int.class`), or `void.class`. * * In the absence of `remove` calls, a class value has a simple * state diagram: uninitialized and initialized. * When `remove` calls are made, * the rules for value observation are more complex. * See the documentation for {@link #remove remove} for more information. * * @param type the type whose class value must be computed or retrieved * @return the current value associated with this `ClassValue`, for the given class or interface * @throws NullPointerException if the argument is null * @see #remove * @see #computeValue */ get(type: Class): T; /** * Removes the associated value for the given class. * If this value is subsequently {@linkplain #get read} for the same class, * its value will be reinitialized by invoking its {@link #computeValue computeValue} method. * This may result in an additional invocation of the * `computeValue` method for the given class. * * In order to explain the interaction between `get` and `remove` calls, * we must model the state transitions of a class value to take into account * the alternation between uninitialized and initialized states. * To do this, number these states sequentially from zero, and note that * uninitialized (or removed) states are numbered with even numbers, * while initialized (or re-initialized) states have odd numbers. * * When a thread `T` removes a class value in state `2N`, * nothing happens, since the class value is already uninitialized. * Otherwise, the state is advanced atomically to `2N+1`. * * When a thread `T` queries a class value in state `2N`, * the thread first attempts to initialize the class value to state `2N+1` * by invoking `computeValue` and installing the resulting value. * * When `T` attempts to install the newly computed value, * if the state is still at `2N`, the class value will be initialized * with the computed value, advancing it to state `2N+1`. * * Otherwise, whether the new state is even or odd, * `T` will discard the newly computed value * and retry the `get` operation. * * Discarding and retrying is an important proviso, * since otherwise `T` could potentially install * a disastrously stale value. For example: * * `T` calls `CV.get(C)` and sees state `2N` * `T` quickly computes a time-dependent value `V0` and gets ready to install it * `T` is hit by an unlucky paging or scheduling event, and goes to sleep for a long time * ...meanwhile, `T2` also calls `CV.get(C)` and sees state `2N` * `T2` quickly computes a similar time-dependent value `V1` and installs it on `CV.get(C)` * `T2` (or a third thread) then calls `CV.remove(C)`, undoing `T2`'s work * the previous actions of `T2` are repeated several times * also, the relevant computed values change over time: `V1`, `V2`, ... * ...meanwhile, `T` wakes up and attempts to install `V0`; this must fail * * We can assume in the above scenario that `CV.computeValue` uses locks to properly * observe the time-dependent states as it computes `V1`, etc. * This does not remove the threat of a stale value, since there is a window of time * between the return of `computeValue` in `T` and the installation * of the new value. No user synchronization is possible during this time. * * @param type the type whose class value must be removed * @throws NullPointerException if the argument is null */ remove(type: Class): void; } /** * Thrown to indicate that an index of some sort (such as to an array, to a * string, or to a vector) is out of range. * * Applications can subclass this class to indicate similar exceptions. * * @author Frank Yellin * @since 1.0 */ export class IndexOutOfBoundsException extends RuntimeException { /** * Constructs an `IndexOutOfBoundsException` with no detail message. */ constructor(); /** * Constructs an `IndexOutOfBoundsException` with the specified detail * message. * * @param s the detail message */ constructor(s: string); /** * Constructs a new `IndexOutOfBoundsException` class with an * argument indicating the illegal index. * * The index is included in this exception's detail message. The * exact presentation format of the detail message is unspecified. * * @param index the illegal index. * @since 9 */ constructor(index: number); } /** * This is the common base class of all Java language record classes. * * More information about records, including descriptions of the * implicitly declared methods synthesized by the compiler, can be * found in section 8.10 of * The Java Language Specification. * * A record class is a shallowly immutable, transparent carrier for * a fixed set of values, called the record components. The Java * language provides concise syntax for declaring record classes, whereby the * record components are declared in the record header. The list of record * components declared in the record header form the record descriptor. * * A record class has the following mandated members: a canonical * constructor, which must provide at least as much access as the record * class and whose descriptor is the same as the record descriptor; * a private final field corresponding to each component, whose name and * type are the same as that of the component; a public accessor method * corresponding to each component, whose name and return type are the same as * that of the component. If not explicitly declared in the body of the record, * implicit implementations for these members are provided. * * The implicit declaration of the canonical constructor has the same accessibility * as the record class and initializes the component fields from the corresponding * constructor arguments. The implicit declaration of the accessor methods returns * the value of the corresponding component field. The implicit declaration of the * {@link Object#equals(Object)}, {@link Object#hashCode()}, and {@link Object#toString()} * methods are derived from all of the component fields. * * The primary reasons to provide an explicit declaration for the * canonical constructor or accessor methods are to validate constructor * arguments, perform defensive copies on mutable components, or normalize groups * of components (such as reducing a rational number to lowest terms.) * * For all record classes, the following invariant must hold: if a record R's * components are `c1, c2, ... cn`, then if a record instance is copied * as follows: * * R copy = new R(r.c1(), r.c2(), ..., r.cn()); * * then it must be the case that `r.equals(copy)`. * * @apiNote * A record class that `implements` {@link java.io.Serializable} is said * to be a serializable record. Serializable records are serialized and * deserialized differently than ordinary serializable objects. During * deserialization the record's canonical constructor is invoked to construct * the record object. Certain serialization-related methods, such as readObject * and writeObject, are ignored for serializable records. More information about * serializable records can be found in the * * Java Object Serialization Specification, Section 1.13, * "Serialization of Records". * * @jls 8.10 Record Types * @since 16 */ export class Record { /** * Indicates whether some other object is "equal to" this one. In addition * to the general contract of {@link Object#equals(Object) Object.equals}, * record classes must further obey the invariant that when * a record instance is "copied" by passing the result of the record component * accessor methods to the canonical constructor, as follows: * * R copy = new R(r.c1(), r.c2(), ..., r.cn()); * * then it must be the case that `r.equals(copy)`. * * @implSpec * The implicitly provided implementation returns `true` if * and only if the argument is an instance of the same record class * as this record, and each component of this record is equal to * the corresponding component of the argument; otherwise, ` * false` is returned. Equality of a component `c` is * determined as follows: * * * If the component is of a reference type, the component is * considered equal if and only if {@link * java.util.Objects#equals(Object,Object) * Objects.equals(this.c, r.c} would return `true`. * * If the component is of a primitive type, using the * corresponding primitive wrapper class `PW` (the * corresponding wrapper class for `int` is ` * java.lang.Integer`, and so on), the component is considered * equal if and only if ` * PW.compare(this.c, r.c)` would return `0`. * * * * Apart from the semantics described above, the precise algorithm * used in the implicitly provided implementation is unspecified * and is subject to change. The implementation may or may not use * calls to the particular methods listed, and may or may not * perform comparisons in the order of component declaration. * * @see java.util.Objects#equals(Object,Object) * * @param obj the reference object with which to compare. * @return `true` if this record is equal to the * argument; `false` otherwise. */ equals(obj: any): boolean; /** * Returns a hash code value for the record. * Obeys the general contract of {@link Object#hashCode Object.hashCode}. * For records, hashing behavior is constrained by the refined contract * of {@link Record#equals Record.equals}, so that any two records * created from the same components must have the same hash code. * * @implSpec * The implicitly provided implementation returns a hash code value derived * by combining appropriate hashes from each component. * The precise algorithm used in the implicitly provided implementation * is unspecified and is subject to change within the above limits. * The resulting integer need not remain consistent from one * execution of an application to another execution of the same * application, even if the hashes of the component values were to * remain consistent in this way. Also, a component of primitive * type may contribute its bits to the hash code differently than * the `hashCode` of its primitive wrapper class. * * @see Object#hashCode() * * @return a hash code value for this record. */ hashCode(): number; /** * Returns a string representation of the record. * In accordance with the general contract of {@link Object#toString()}, * the `toString` method returns a string that * "textually represents" this record. The result should * be a concise but informative representation that is easy for a * person to read. * * In addition to this general contract, record classes must further * participate in the invariant that any two records which are * {@linkplain Record#equals(Object) equal} must produce equal * strings. This invariant is necessarily relaxed in the rare * case where corresponding equal component values might fail * to produce equal strings for themselves. * * @implSpec * The implicitly provided implementation returns a string which * contains the name of the record class, the names of components * of the record, and string representations of component values, * so as to fulfill the contract of this method. * The precise format produced by this implicitly provided implementation * is subject to change, so the present syntax should not be parsed * by applications to recover record component values. * * @see Object#toString() * * @return a string representation of the object. */ toString(): string; } /** * Thrown when an application tries to call an abstract method. * Normally, this error is caught by the compiler; this error can * only occur at run time if the definition of some class has * incompatibly changed since the currently executing method was last * compiled. * * @since 1.0 */ export class AbstractMethodError extends IncompatibleClassChangeError { /** * Constructs an `AbstractMethodError` with no detail message. */ constructor(); /** * Constructs an `AbstractMethodError` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); } export class ThreadGroup extends UncaughtExceptionHandler { /** * Constructs a new thread group. The parent of this new group is * the thread group of the currently running thread. * * The `checkAccess` method of the parent thread group is * called with no arguments; this may result in a security exception. * * @param name the name of the new thread group. * @throws SecurityException if the current thread cannot create a * thread in the specified thread group. * @see java.lang.ThreadGroup#checkAccess() * @since 1.0 */ constructor(name: string); /** * Creates a new thread group. The parent of this new group is the * specified thread group. * * The `checkAccess` method of the parent thread group is * called with no arguments; this may result in a security exception. * * @param parent the parent thread group. * @param name the name of the new thread group. * @throws NullPointerException if the thread group argument is * `null`. * @throws SecurityException if the current thread cannot create a * thread in the specified thread group. * @see java.lang.SecurityException * @see java.lang.ThreadGroup#checkAccess() * @since 1.0 */ constructor(parent: ThreadGroup, name: string); /** * Returns the name of this thread group. * * @return the name of this thread group. * @since 1.0 */ get name(): string; /** * Returns the parent of this thread group. * * First, if the parent is not `null`, the * `checkAccess` method of the parent thread group is * called with no arguments; this may result in a security exception. * * @return the parent of this thread group. The top-level thread group * is the only thread group whose parent is `null`. * @throws SecurityException if the current thread cannot modify * this thread group. * @see java.lang.ThreadGroup#checkAccess() * @see java.lang.SecurityException * @see java.lang.RuntimePermission * @since 1.0 */ get parent(): ThreadGroup; /** * Returns the maximum priority of this thread group. Threads that are * part of this group cannot have a higher priority than the maximum * priority. * * @return the maximum priority that a thread in this thread group * can have. * @see #setMaxPriority * @since 1.0 */ get maxPriority(): number; /** * Tests if this thread group is a daemon thread group. A * daemon thread group is automatically destroyed when its last * thread is stopped or its last thread group is destroyed. * * @return `true` if this thread group is a daemon thread group; * `false` otherwise. * @since 1.0 * * @deprecated The API and mechanism for destroying a ThreadGroup is inherently * flawed. The ability to explicitly or automatically destroy a * thread group, and the concept of daemon thread group, will be * removed in a future release. */ isDaemon(): boolean; /** * Tests if this thread group has been destroyed. * * @return true if this object is destroyed * @since 1.1 * * @deprecated The API and mechanism for destroying a ThreadGroup is inherently * flawed. The ability to explicitly or automatically destroy a * thread group will be removed in a future release. */ isDestroyed(): boolean; /** * Changes the daemon status of this thread group. * * First, the `checkAccess` method of this thread group is * called with no arguments; this may result in a security exception. * * A daemon thread group is automatically destroyed when its last * thread is stopped or its last thread group is destroyed. * * @param daemon if `true`, marks this thread group as * a daemon thread group; otherwise, marks this * thread group as normal. * @throws SecurityException if the current thread cannot modify * this thread group. * @see java.lang.SecurityException * @see java.lang.ThreadGroup#checkAccess() * @since 1.0 * * @deprecated The API and mechanism for destroying a ThreadGroup is inherently * flawed. The ability to explicitly or automatically destroy a * thread group, and the concept of daemon thread group, will be * removed in a future release. */ setDaemon(daemon: boolean): void; /** * Sets the maximum priority of the group. Threads in the thread * group that already have a higher priority are not affected. * * First, the `checkAccess` method of this thread group is * called with no arguments; this may result in a security exception. * * If the `pri` argument is less than * {@link Thread#MIN_PRIORITY} or greater than * {@link Thread#MAX_PRIORITY}, the maximum priority of the group * remains unchanged. * * Otherwise, the priority of this ThreadGroup object is set to the * smaller of the specified `pri` and the maximum permitted * priority of the parent of this thread group. (If this thread group * is the system thread group, which has no parent, then its maximum * priority is simply set to `pri`.) Then this method is * called recursively, with `pri` as its argument, for * every thread group that belongs to this thread group. * * @param pri the new priority of the thread group. * @throws SecurityException if the current thread cannot modify * this thread group. * @see #getMaxPriority * @see java.lang.SecurityException * @see java.lang.ThreadGroup#checkAccess() * @since 1.0 */ set maxPriority(maxPriority: number); /** * Tests if this thread group is either the thread group * argument or one of its ancestor thread groups. * * @param g a thread group. * @return `true` if this thread group is the thread group * argument or one of its ancestor thread groups; * `false` otherwise. * @since 1.0 */ parentOf(g: ThreadGroup): boolean; /** * Determines if the currently running thread has permission to * modify this thread group. * * If there is a security manager, its `checkAccess` method * is called with this thread group as its argument. This may result * in throwing a `SecurityException`. * * @throws SecurityException if the current thread is not allowed to * access this thread group. * @see java.lang.SecurityManager#checkAccess(java.lang.ThreadGroup) * @since 1.0 */ checkAccess(): void; /** * Returns an estimate of the number of active threads in this thread * group and its subgroups. Recursively iterates over all subgroups in * this thread group. * * The value returned is only an estimate because the number of * threads may change dynamically while this method traverses internal * data structures, and might be affected by the presence of certain * system threads. This method is intended primarily for debugging * and monitoring purposes. * * @return an estimate of the number of active threads in this thread * group and in any other thread group that has this thread * group as an ancestor * * @since 1.0 */ activeCount(): number; /** * Copies into the specified array every active thread in this * thread group and its subgroups. * * An invocation of this method behaves in exactly the same * way as the invocation * * * {@linkplain #enumerate(Thread[], boolean) enumerate}`(list, true)` * * * @param list * an array into which to put the list of threads * * @return the number of threads put into the array * * @throws SecurityException * if {@linkplain #checkAccess checkAccess} determines that * the current thread cannot access this thread group * * @since 1.0 */ enumerate(list: Thread[]): number; /** * Copies into the specified array every active thread in this * thread group. If `recurse` is `true`, * this method recursively enumerates all subgroups of this * thread group and references to every active thread in these * subgroups are also included. If the array is too short to * hold all the threads, the extra threads are silently ignored. * * An application might use the {@linkplain #activeCount activeCount} * method to get an estimate of how big the array should be, however * if the array is too short to hold all the threads, the extra threads * are silently ignored. If it is critical to obtain every active * thread in this thread group, the caller should verify that the returned * int value is strictly less than the length of `list`. * * Due to the inherent race condition in this method, it is recommended * that the method only be used for debugging and monitoring purposes. * * @param list * an array into which to put the list of threads * * @param recurse * if `true`, recursively enumerate all subgroups of this * thread group * * @return the number of threads put into the array * * @throws SecurityException * if {@linkplain #checkAccess checkAccess} determines that * the current thread cannot access this thread group * * @since 1.0 */ enumerate(list: Thread[], recurse: boolean): number; /** * Returns an estimate of the number of active groups in this * thread group and its subgroups. Recursively iterates over * all subgroups in this thread group. * * The value returned is only an estimate because the number of * thread groups may change dynamically while this method traverses * internal data structures. This method is intended primarily for * debugging and monitoring purposes. * * @return the number of active thread groups with this thread group as * an ancestor * * @since 1.0 */ activeGroupCount(): number; /** * Copies into the specified array references to every active * subgroup in this thread group and its subgroups. * * An invocation of this method behaves in exactly the same * way as the invocation * * * {@linkplain #enumerate(ThreadGroup[], boolean) enumerate}`(list, true)` * * * @param list * an array into which to put the list of thread groups * * @return the number of thread groups put into the array * * @throws SecurityException * if {@linkplain #checkAccess checkAccess} determines that * the current thread cannot access this thread group * * @since 1.0 */ enumerate(list: ThreadGroup[]): number; /** * Copies into the specified array references to every active * subgroup in this thread group. If `recurse` is * `true`, this method recursively enumerates all subgroups of this * thread group and references to every active thread group in these * subgroups are also included. * * An application might use the * {@linkplain #activeGroupCount activeGroupCount} method to * get an estimate of how big the array should be, however if the * array is too short to hold all the thread groups, the extra thread * groups are silently ignored. If it is critical to obtain every * active subgroup in this thread group, the caller should verify that * the returned int value is strictly less than the length of * `list`. * * Due to the inherent race condition in this method, it is recommended * that the method only be used for debugging and monitoring purposes. * * @param list * an array into which to put the list of thread groups * * @param recurse * if `true`, recursively enumerate all subgroups * * @return the number of thread groups put into the array * * @throws SecurityException * if {@linkplain #checkAccess checkAccess} determines that * the current thread cannot access this thread group * * @since 1.0 */ enumerate(list: ThreadGroup[], recurse: boolean): number; /** * Stops all threads in this thread group. * * First, the `checkAccess` method of this thread group is * called with no arguments; this may result in a security exception. * * This method then calls the `stop` method on all the * threads in this thread group and in all of its subgroups. * * @throws SecurityException if the current thread is not allowed * to access this thread group or any of the threads in * the thread group. * @see java.lang.SecurityException * @see java.lang.Thread#stop() * @see java.lang.ThreadGroup#checkAccess() * @since 1.0 * @deprecated This method is inherently unsafe. See * {@link Thread#stop} for details. */ stop(): void; /** * Interrupts all threads in this thread group. * * First, the `checkAccess` method of this thread group is * called with no arguments; this may result in a security exception. * * This method then calls the `interrupt` method on all the * threads in this thread group and in all of its subgroups. * * @throws SecurityException if the current thread is not allowed * to access this thread group or any of the threads in * the thread group. * @see java.lang.Thread#interrupt() * @see java.lang.SecurityException * @see java.lang.ThreadGroup#checkAccess() * @since 1.2 */ interrupt(): void; /** * Suspends all threads in this thread group. * * First, the `checkAccess` method of this thread group is * called with no arguments; this may result in a security exception. * * This method then calls the `suspend` method on all the * threads in this thread group and in all of its subgroups. * * @throws SecurityException if the current thread is not allowed * to access this thread group or any of the threads in * the thread group. * @see java.lang.Thread#suspend() * @see java.lang.SecurityException * @see java.lang.ThreadGroup#checkAccess() * @since 1.0 * @deprecated This method is inherently deadlock-prone. See * {@link Thread#suspend} for details. */ suspend(): void; /** * Resumes all threads in this thread group. * * First, the `checkAccess` method of this thread group is * called with no arguments; this may result in a security exception. * * This method then calls the `resume` method on all the * threads in this thread group and in all of its sub groups. * * @throws SecurityException if the current thread is not allowed to * access this thread group or any of the threads in the * thread group. * @see java.lang.SecurityException * @see java.lang.Thread#resume() * @see java.lang.ThreadGroup#checkAccess() * @since 1.0 * @deprecated This method is used solely in conjunction with * `Thread.suspend` and `ThreadGroup.suspend`, * both of which have been deprecated, as they are inherently * deadlock-prone. See {@link Thread#suspend} for details. */ resume(): void; /** * Destroys this thread group and all of its subgroups. This thread * group must be empty, indicating that all threads that had been in * this thread group have since stopped. * * First, the `checkAccess` method of this thread group is * called with no arguments; this may result in a security exception. * * @throws IllegalThreadStateException if the thread group is not * empty or if the thread group has already been destroyed. * @throws SecurityException if the current thread cannot modify this * thread group. * @see java.lang.ThreadGroup#checkAccess() * @since 1.0 * * @deprecated The API and mechanism for destroying a ThreadGroup is inherently * flawed. The ability to explicitly or automatically destroy a * thread group will be removed in a future release. */ destroy(): void; /** * Prints information about this thread group to the standard * output. This method is useful only for debugging. * * @since 1.0 */ list(): void; /** * Called by the Java Virtual Machine when a thread in this * thread group stops because of an uncaught exception, and the thread * does not have a specific {@link Thread.UncaughtExceptionHandler} * installed. * * The `uncaughtException` method of * `ThreadGroup` does the following: * * If this thread group has a parent thread group, the * `uncaughtException` method of that parent is called * with the same two arguments. * Otherwise, this method checks to see if there is a * {@linkplain Thread#getDefaultUncaughtExceptionHandler default * uncaught exception handler} installed, and if so, its * `uncaughtException` method is called with the same * two arguments. * Otherwise, this method determines if the `Throwable` * argument is an instance of {@link ThreadDeath}. If so, nothing * special is done. Otherwise, a message containing the * thread's name, as returned from the thread's {@link * Thread#getName getName} method, and a stack backtrace, * using the `Throwable`'s {@link * Throwable#printStackTrace printStackTrace} method, is * printed to the {@linkplain System#err standard error stream}. * * * Applications can override this method in subclasses of * `ThreadGroup` to provide alternative handling of * uncaught exceptions. * * @param t the thread that is about to exit. * @param e the uncaught exception. * @since 1.0 */ uncaughtException(t: Thread, e: Throwable): void; /** * Used by VM to control lowmem implicit suspension. * * @param b boolean to allow or disallow suspension * @return true on success * @since 1.1 * @deprecated The definition of this call depends on {@link #suspend}, * which is deprecated. Further, the behavior of this call * was never specified. */ allowThreadSuspension(b: boolean): boolean; /** * Returns a string representation of this Thread group. * * @return a string representation of this thread group. * @since 1.0 */ toString(): string; } export class CloneNotSupportedException extends Exception { /** * Constructs a `CloneNotSupportedException` with no * detail message. */ constructor(); /** * Constructs a `CloneNotSupportedException` with the * specified detail message. * * @param s the detail message. */ constructor(s: string); } /** * Signals that the class doesn't have a field of a specified name. * * @since 1.1 */ export class NoSuchFieldException extends ReflectiveOperationException { /** * Constructor. */ constructor(); /** * Constructor with a detail message. * * @param s the detail message */ constructor(s: string); } /** * Thrown when an exceptional arithmetic condition has occurred. For * example, an integer "divide by zero" throws an * instance of this class. * * `ArithmeticException` objects may be constructed by the * virtual machine as if {@linkplain Throwable#Throwable(String, * Throwable, boolean, boolean) suppression were disabled and/or the * stack trace was not writable}. * * @since 1.0 */ export class ArithmeticException extends RuntimeException { /** * Constructs an `ArithmeticException` with no detail * message. */ constructor(); /** * Constructs an `ArithmeticException` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); } export class ThreadDeath extends Error { /** * Constructs a `ThreadDeath`. */ constructor(); } /** * A mutable sequence of characters. This class provides an API compatible * with `StringBuffer`, but with no guarantee of synchronization. * This class is designed for use as a drop-in replacement for * `StringBuffer` in places where the string buffer was being * used by a single thread (as is generally the case). Where possible, * it is recommended that this class be used in preference to * `StringBuffer` as it will be faster under most implementations. * * The principal operations on a `StringBuilder` are the * `append` and `insert` methods, which are * overloaded so as to accept data of any type. Each effectively * converts a given datum to a string and then appends or inserts the * characters of that string to the string builder. The * `append` method always adds these characters at the end * of the builder; the `insert` method adds the characters at * a specified point. * * For example, if `z` refers to a string builder object * whose current contents are "`start`", then * the method call `z.append("le")` would cause the string * builder to contain "`startle`", whereas * `z.insert(4, "le")` would alter the string builder to * contain "`starlet`". * * In general, if sb refers to an instance of a `StringBuilder`, * then `sb.append(x)` has the same effect as * `sb.insert(sb.length(), x)`. * * Every string builder has a capacity. As long as the length of the * character sequence contained in the string builder does not exceed * the capacity, it is not necessary to allocate a new internal * buffer. If the internal buffer overflows, it is automatically made larger. * * Instances of `StringBuilder` are not safe for * use by multiple threads. If such synchronization is required then it is * recommended that {@link java.lang.StringBuffer} be used. * * Unless otherwise noted, passing a `null` argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * * @apiNote * `StringBuilder` implements `Comparable` but does not override * {@link Object#equals equals}. Thus, the natural ordering of `StringBuilder` * is inconsistent with equals. Care should be exercised if `StringBuilder` * objects are used as keys in a `SortedMap` or elements in a `SortedSet`. * See {@link Comparable}, {@link java.util.SortedMap SortedMap}, or * {@link java.util.SortedSet SortedSet} for more information. * * @author Michael McCloskey * @see java.lang.StringBuffer * @see java.lang.String * @since 1.5 */ export class StringBuilder extends Serializable { /** * Constructs a string builder with no characters in it and an * initial capacity of 16 characters. */ constructor(); /** * Constructs a string builder with no characters in it and an * initial capacity specified by the `capacity` argument. * * @param capacity the initial capacity. * @throws NegativeArraySizeException if the `capacity` * argument is less than `0`. */ constructor(capacity: number); /** * Constructs a string builder initialized to the contents of the * specified string. The initial capacity of the string builder is * `16` plus the length of the string argument. * * @param str the initial contents of the buffer. */ constructor(str: string); /** * Constructs a string builder that contains the same characters * as the specified `CharSequence`. The initial capacity of * the string builder is `16` plus the length of the * `CharSequence` argument. * * @param seq the sequence to copy. */ constructor(seq: CharSequence); /** * Compares two `StringBuilder` instances lexicographically. This method * follows the same rules for lexicographical comparison as defined in the * {@linkplain java.lang.CharSequence#compare(java.lang.CharSequence, * java.lang.CharSequence) CharSequence.compare(this, another)} method. * * * For finer-grained, locale-sensitive String comparison, refer to * {@link java.text.Collator}. * * @param another the `StringBuilder` to be compared with * * @return the value `0` if this `StringBuilder` contains the same * character sequence as that of the argument `StringBuilder`; a negative integer * if this `StringBuilder` is lexicographically less than the * `StringBuilder` argument; or a positive integer if this `StringBuilder` * is lexicographically greater than the `StringBuilder` argument. * * @since 11 */ compareTo(another: StringBuilder): number; append(obj: any): StringBuilder; append(str: string): StringBuilder; /** * Appends the specified `StringBuffer` to this sequence. * * The characters of the `StringBuffer` argument are appended, * in order, to this sequence, increasing the * length of this sequence by the length of the argument. * If `sb` is `null`, then the four characters * `"null"` are appended to this sequence. * * Let n be the length of this character sequence just prior to * execution of the `append` method. Then the character at index * k in the new character sequence is equal to the character at * index k in the old character sequence, if k is less than * n; otherwise, it is equal to the character at index k-n * in the argument `sb`. * * @param sb the `StringBuffer` to append. * @return a reference to this object. */ append(sb: StringBuffer): StringBuilder; append(s: CharSequence): StringBuilder; /** * @throws IndexOutOfBoundsException {@inheritDoc} */ append(s: CharSequence, start: number, end: number): StringBuilder; append(str: string[]): StringBuilder; /** * @throws IndexOutOfBoundsException {@inheritDoc} */ append(str: string[], offset: number, len: number): StringBuilder; append(b: boolean): StringBuilder; append(i: number): StringBuilder; /** * @since 1.5 */ appendCodePoint(codePoint: number): StringBuilder; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ delete(start: number, end: number): StringBuilder; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ deleteCharAt(index: number): StringBuilder; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ replace(start: number, end: number, str: string): StringBuilder; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(index: number, str: string[], offset: number, len: number): StringBuilder; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, obj: any): StringBuilder; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, str: string): StringBuilder; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, str: string[]): StringBuilder; /** * @throws IndexOutOfBoundsException {@inheritDoc} */ insert(dstOffset: number, s: CharSequence): StringBuilder; /** * @throws IndexOutOfBoundsException {@inheritDoc} */ insert(dstOffset: number, s: CharSequence, start: number, end: number): StringBuilder; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, b: boolean): StringBuilder; /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ insert(offset: number, i: number): StringBuilder; indexOf(str: string): number; indexOf(str: string, fromIndex: number): number; lastIndexOf(str: string): number; lastIndexOf(str: string, fromIndex: number): number; reverse(): StringBuilder; toString(): string; /** * Compares this object with the specified object for order. Returns a * negative integer, zero, or a positive integer as this object is less * than, equal to, or greater than the specified object. * * The implementor must ensure * `sgn(x.compareTo(y)) == -sgn(y.compareTo(x))` * for all `x` and `y`. (This * implies that `x.compareTo(y)` must throw an exception iff * `y.compareTo(x)` throws an exception.) * * The implementor must also ensure that the relation is transitive: * `(x.compareTo(y) > 0 && y.compareTo(z) > 0)` implies * `x.compareTo(z) > 0`. * * Finally, the implementor must ensure that `x.compareTo(y)==0` * implies that `sgn(x.compareTo(z)) == sgn(y.compareTo(z))`, for * all `z`. * * It is strongly recommended, but not strictly required that * `(x.compareTo(y)==0) == (x.equals(y))`. Generally speaking, any * class that implements the `Comparable` interface and violates * this condition should clearly indicate this fact. The recommended * language is "Note: this class has a natural ordering that is * inconsistent with equals." * * In the foregoing description, the notation * `sgn(`expression`)` designates the mathematical * signum function, which is defined to return one of `-1`, * `0`, or `1` according to whether the value of * expression is negative, zero, or positive, respectively. * * @param o the object to be compared. * @return a negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. * * @throws NullPointerException if the specified object is null * @throws ClassCastException if the specified object's type prevents it * from being compared to this object. */ compareTo(o: T): number; } export interface StringBuilder extends Serializable, Comparable, CharSequence {} /** * A class loader is an object that is responsible for loading classes. The * class `ClassLoader` is an abstract class. Given the binary name of a class, a class loader should attempt to * locate or generate data that constitutes a definition for the class. A * typical strategy is to transform the name into a file name and then read a * "class file" of that name from a file system. * * Every {@link java.lang.Class Class} object contains a {@link * Class#getClassLoader() reference} to the `ClassLoader` that defined * it. * * `Class` objects for array classes are not created by class * loaders, but are created automatically as required by the Java runtime. * The class loader for an array class, as returned by {@link * Class#getClassLoader()} is the same as the class loader for its element * type; if the element type is a primitive type, then the array class has no * class loader. * * Applications implement subclasses of `ClassLoader` in order to * extend the manner in which the Java virtual machine dynamically loads * classes. * * Class loaders may typically be used by security managers to indicate * security domains. * * In addition to loading classes, a class loader is also responsible for * locating resources. A resource is some data (a "`.class`" file, * configuration data, or an image for example) that is identified with an * abstract '/'-separated path name. Resources are typically packaged with an * application or library so that they can be located by code in the * application or library. In some cases, the resources are included so that * they can be located by other libraries. * * The `ClassLoader` class uses a delegation model to search for * classes and resources. Each instance of `ClassLoader` has an * associated parent class loader. When requested to find a class or * resource, a `ClassLoader` instance will usually delegate the search * for the class or resource to its parent class loader before attempting to * find the class or resource itself. * * Class loaders that support concurrent loading of classes are known as * {@linkplain #isRegisteredAsParallelCapable() parallel capable} class * loaders and are required to register themselves at their class initialization * time by invoking the {@link * #registerAsParallelCapable ClassLoader.registerAsParallelCapable} * method. Note that the `ClassLoader` class is registered as parallel * capable by default. However, its subclasses still need to register themselves * if they are parallel capable. * In environments in which the delegation model is not strictly * hierarchical, class loaders need to be parallel capable, otherwise class * loading can lead to deadlocks because the loader lock is held for the * duration of the class loading process (see {@link #loadClass * loadClass} methods). * * Run-time Built-in Class Loaders * * The Java run-time has the following built-in class loaders: * * * Bootstrap class loader. * It is the virtual machine's built-in class loader, typically represented * as `null`, and does not have a parent. * {@linkplain #getPlatformClassLoader() Platform class loader}. * The platform class loader is responsible for loading the * platform classes. Platform classes include Java SE platform APIs, * their implementation classes and JDK-specific run-time classes that are * defined by the platform class loader or its ancestors. * The platform class loader can be used as the parent of a `ClassLoader` * instance. * To allow for upgrading/overriding of modules defined to the platform * class loader, and where upgraded modules read modules defined to class * loaders other than the platform class loader and its ancestors, then * the platform class loader may have to delegate to other class loaders, * the application class loader for example. * In other words, classes in named modules defined to class loaders * other than the platform class loader and its ancestors may be visible * to the platform class loader. * {@linkplain #getSystemClassLoader() System class loader}. * It is also known as application class loader and is distinct * from the platform class loader. * The system class loader is typically used to define classes on the * application class path, module path, and JDK-specific tools. * The platform class loader is the parent or an ancestor of the system class * loader, so the system class loader can load platform classes by delegating * to its parent. * * * Normally, the Java virtual machine loads classes from the local file * system in a platform-dependent manner. * However, some classes may not originate from a file; they may originate * from other sources, such as the network, or they could be constructed by an * application. The method {@link #defineClass(String, byte[], int, int) * defineClass} converts an array of bytes into an instance of class * `Class`. Instances of this newly defined class can be created using * {@link Class#newInstance Class.newInstance}. * * The methods and constructors of objects created by a class loader may * reference other classes. To determine the class(es) referred to, the Java * virtual machine invokes the {@link #loadClass loadClass} method of * the class loader that originally created the class. * * For example, an application could create a network class loader to * download class files from a server. Sample code might look like: * * * ClassLoader loader = new NetworkClassLoader(host, port); * Object main = loader.loadClass("Main", true).newInstance(); *  . . . * * * The network class loader subclass must define the methods {@link * #findClass findClass} and `loadClassData` to load a class * from the network. Once it has downloaded the bytes that make up the class, * it should use the method {@link #defineClass defineClass} to * create a class instance. A sample implementation is: * * * class NetworkClassLoader extends ClassLoader { * String host; * int port; * * public Class findClass(String name) { * byte[] b = loadClassData(name); * return defineClass(name, b, 0, b.length); * } * * private byte[] loadClassData(String name) { * // load the class data from the connection *  . . . * } * } * * * Binary names * * Any class name provided as a `String` parameter to methods in * `ClassLoader` must be a binary name as defined by * The Java Language Specification. * * Examples of valid class names include: * * "java.lang.String" * "javax.swing.JSpinner$DefaultEditor" * "java.security.KeyStore$Builder$FileBuilder$1" * "java.net.URLClassLoader$3$1" * * * Any package name provided as a `String` parameter to methods in * `ClassLoader` must be either the empty string (denoting an unnamed package) * or a fully qualified name as defined by * The Java Language Specification. * * @jls 6.7 Fully Qualified Names * @jls 13.1 The Form of a Binary * @see #resolveClass(Class) * @since 1.0 * @revised 9 */ export class ClassLoader { /** * Returns the name of this class loader or `null` if * this class loader is not named. * * @apiNote This method is non-final for compatibility. If this * method is overridden, this method must return the same name * as specified when this class loader was instantiated. * * @return name of this class loader; or `null` if * this class loader is not named. * * @since 9 */ get name(): string; /** * Loads the class with the specified binary name. * This method searches for classes in the same manner as the {@link * #loadClass(String, boolean)} method. It is invoked by the Java virtual * machine to resolve class references. Invoking this method is equivalent * to invoking {@link #loadClass(String, boolean) loadClass(name, * false)}. * * @param name * The binary name of the class * * @return The resulting `Class` object * * @throws ClassNotFoundException * If the class was not found */ loadClass(name: string): Class; /** * Finds the resource with the given name. A resource is some data * (images, audio, text, etc) that can be accessed by class code in a way * that is independent of the location of the code. * * The name of a resource is a '`/`'-separated path name that * identifies the resource. * * Resources in named modules are subject to the encapsulation rules * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. * Additionally, and except for the special case where the resource has a * name ending with "`.class`", this method will only find resources in * packages of named modules when the package is {@link Module#isOpen(String) * opened} unconditionally (even if the caller of this method is in the * same module as the resource). * * @implSpec The default implementation will first search the parent class * loader for the resource; if the parent is `null` the path of the * class loader built into the virtual machine is searched. If not found, * this method will invoke {@link #findResource(String)} to find the resource. * * @apiNote Where several modules are defined to the same class loader, * and where more than one module contains a resource with the given name, * then the ordering that modules are searched is not specified and may be * very unpredictable. * When overriding this method it is recommended that an implementation * ensures that any delegation is consistent with the {@link * #getResources(java.lang.String) getResources(String)} method. * * @param name * The resource name * * @return `URL` object for reading the resource; `null` if * the resource could not be found, a `URL` could not be * constructed to locate the resource, the resource is in a package * that is not opened unconditionally, or access to the resource is * denied by the security manager. * * @throws NullPointerException If `name` is `null` * * @since 1.1 * @revised 9 */ getResource(name: string): URL; /** * Finds all the resources with the given name. A resource is some data * (images, audio, text, etc) that can be accessed by class code in a way * that is independent of the location of the code. * * The name of a resource is a `/`-separated path name that * identifies the resource. * * Resources in named modules are subject to the encapsulation rules * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. * Additionally, and except for the special case where the resource has a * name ending with "`.class`", this method will only find resources in * packages of named modules when the package is {@link Module#isOpen(String) * opened} unconditionally (even if the caller of this method is in the * same module as the resource). * * @implSpec The default implementation will first search the parent class * loader for the resource; if the parent is `null` the path of the * class loader built into the virtual machine is searched. It then * invokes {@link #findResources(String)} to find the resources with the * name in this class loader. It returns an enumeration whose elements * are the URLs found by searching the parent class loader followed by * the elements found with `findResources`. * * @apiNote Where several modules are defined to the same class loader, * and where more than one module contains a resource with the given name, * then the ordering is not specified and may be very unpredictable. * When overriding this method it is recommended that an * implementation ensures that any delegation is consistent with the {@link * #getResource(java.lang.String) getResource(String)} method. This should * ensure that the first element returned by the Enumeration's * `nextElement` method is the same resource that the * `getResource(String)` method would return. * * @param name * The resource name * * @return An enumeration of {@link java.net.URL URL} objects for the * resource. If no resources could be found, the enumeration will * be empty. Resources for which a `URL` cannot be * constructed, are in a package that is not opened * unconditionally, or access to the resource is denied by the * security manager, are not returned in the enumeration. * * @throws IOException * If I/O errors occur * @throws NullPointerException If `name` is `null` * * @since 1.2 * @revised 9 */ getResources(name: string): Enumeration; /** * Returns a stream whose elements are the URLs of all the resources with * the given name. A resource is some data (images, audio, text, etc) that * can be accessed by class code in a way that is independent of the * location of the code. * * The name of a resource is a `/`-separated path name that * identifies the resource. * * The resources will be located when the returned stream is evaluated. * If the evaluation results in an `IOException` then the I/O * exception is wrapped in an {@link UncheckedIOException} that is then * thrown. * * Resources in named modules are subject to the encapsulation rules * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. * Additionally, and except for the special case where the resource has a * name ending with "`.class`", this method will only find resources in * packages of named modules when the package is {@link Module#isOpen(String) * opened} unconditionally (even if the caller of this method is in the * same module as the resource). * * @implSpec The default implementation invokes {@link #getResources(String) * getResources} to find all the resources with the given name and returns * a stream with the elements in the enumeration as the source. * * @apiNote When overriding this method it is recommended that an * implementation ensures that any delegation is consistent with the {@link * #getResource(java.lang.String) getResource(String)} method. This should * ensure that the first element returned by the stream is the same * resource that the `getResource(String)` method would return. * * @param name * The resource name * * @return A stream of resource {@link java.net.URL URL} objects. If no * resources could be found, the stream will be empty. Resources * for which a `URL` cannot be constructed, are in a package * that is not opened unconditionally, or access to the resource * is denied by the security manager, will not be in the stream. * * @throws NullPointerException If `name` is `null` * * @since 9 */ resources(name: string): Stream; /** * Returns `true` if this class loader is registered as * {@linkplain #registerAsParallelCapable parallel capable}, otherwise * `false`. * * @return `true` if this class loader is parallel capable, * otherwise `false`. * * @see #registerAsParallelCapable() * * @since 9 */ isRegisteredAsParallelCapable(): boolean; /** * Find a resource of the specified name from the search path used to load * classes. This method locates the resource through the system class * loader (see {@link #getSystemClassLoader()}). * * Resources in named modules are subject to the encapsulation rules * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. * Additionally, and except for the special case where the resource has a * name ending with "`.class`", this method will only find resources in * packages of named modules when the package is {@link Module#isOpen(String) * opened} unconditionally. * * @param name * The resource name * * @return A {@link java.net.URL URL} to the resource; ` * null` if the resource could not be found, a URL could not be * constructed to locate the resource, the resource is in a package * that is not opened unconditionally or access to the resource is * denied by the security manager. * * @since 1.1 * @revised 9 */ static getSystemResource(name: string): URL; /** * Finds all resources of the specified name from the search path used to * load classes. The resources thus found are returned as an * {@link java.util.Enumeration Enumeration} of {@link * java.net.URL URL} objects. * * The search order is described in the documentation for {@link * #getSystemResource(String)}. * * Resources in named modules are subject to the encapsulation rules * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. * Additionally, and except for the special case where the resource has a * name ending with "`.class`", this method will only find resources in * packages of named modules when the package is {@link Module#isOpen(String) * opened} unconditionally. * * @param name * The resource name * * @return An enumeration of {@link java.net.URL URL} objects for * the resource. If no resources could be found, the enumeration * will be empty. Resources for which a `URL` cannot be * constructed, are in a package that is not opened unconditionally, * or access to the resource is denied by the security manager, * are not returned in the enumeration. * * @throws IOException * If I/O errors occur * * @since 1.2 * @revised 9 */ static getSystemResources(name: string): Enumeration; /** * Returns an input stream for reading the specified resource. * * The search order is described in the documentation for {@link * #getResource(String)}. * * Resources in named modules are subject to the encapsulation rules * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. * Additionally, and except for the special case where the resource has a * name ending with "`.class`", this method will only find resources in * packages of named modules when the package is {@link Module#isOpen(String) * opened} unconditionally. * * @param name * The resource name * * @return An input stream for reading the resource; `null` if the * resource could not be found, the resource is in a package that * is not opened unconditionally, or access to the resource is * denied by the security manager. * * @throws NullPointerException If `name` is `null` * * @since 1.1 * @revised 9 */ getResourceAsStream(name: string): InputStream; /** * Open for reading, a resource of the specified name from the search path * used to load classes. This method locates the resource through the * system class loader (see {@link #getSystemClassLoader()}). * * Resources in named modules are subject to the encapsulation rules * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. * Additionally, and except for the special case where the resource has a * name ending with "`.class`", this method will only find resources in * packages of named modules when the package is {@link Module#isOpen(String) * opened} unconditionally. * * @param name * The resource name * * @return An input stream for reading the resource; `null` if the * resource could not be found, the resource is in a package that * is not opened unconditionally, or access to the resource is * denied by the security manager. * * @since 1.1 * @revised 9 */ static getSystemResourceAsStream(name: string): InputStream; /** * Returns the parent class loader for delegation. Some implementations may * use `null` to represent the bootstrap class loader. This method * will return `null` in such implementations if this class loader's * parent is the bootstrap class loader. * * @return The parent `ClassLoader` * * @throws SecurityException * If a security manager is present, and the caller's class loader * is not `null` and is not an ancestor of this class loader, * and the caller does not have the * {@link RuntimePermission}`("getClassLoader")` * * @since 1.2 */ get parent(): ClassLoader; /** * Returns the unnamed `Module` for this class loader. * * @return The unnamed Module for this class loader * * @see Module#isNamed() * @since 9 */ get unnamedModule(): Module; /** * Returns the platform class loader. All * platform classes are visible to * the platform class loader. * * @implNote The name of the builtin platform class loader is * `"platform"`. * * @return The platform `ClassLoader`. * * @throws SecurityException * If a security manager is present, and the caller's class loader is * not `null`, and the caller's class loader is not the same * as or an ancestor of the platform class loader, * and the caller does not have the * {@link RuntimePermission}`("getClassLoader")` * * @since 9 */ static get platformClassLoader(): ClassLoader; /** * Returns the system class loader. This is the default * delegation parent for new `ClassLoader` instances, and is * typically the class loader used to start the application. * * This method is first invoked early in the runtime's startup * sequence, at which point it creates the system class loader. This * class loader will be the context class loader for the main application * thread (for example, the thread that invokes the `main` method of * the main class). * * The default system class loader is an implementation-dependent * instance of this class. * * If the system property "{@systemProperty java.system.class.loader}" * is defined when this method is first invoked then the value of that * property is taken to be the name of a class that will be returned as the * system class loader. The class is loaded using the default system class * loader and must define a public constructor that takes a single parameter * of type `ClassLoader` which is used as the delegation parent. An * instance is then created using this constructor with the default system * class loader as the parameter. The resulting class loader is defined * to be the system class loader. During construction, the class loader * should take great care to avoid calling `getSystemClassLoader()`. * If circular initialization of the system class loader is detected then * an `IllegalStateException` is thrown. * * @implNote The system property to override the system class loader is not * examined until the VM is almost fully initialized. Code that executes * this method during startup should take care not to cache the return * value until the system is fully initialized. * * The name of the built-in system class loader is `"app"`. * The system property "`java.class.path`" is read during early * initialization of the VM to determine the class path. * An empty value of "`java.class.path`" property is interpreted * differently depending on whether the initial module (the module * containing the main class) is named or unnamed: * If named, the built-in system class loader will have no class path and * will search for classes and resources using the application module path; * otherwise, if unnamed, it will set the class path to the current * working directory. * * JAR files on the class path may contain a `Class-Path` manifest * attribute to specify dependent JAR files to be included in the class path. * `Class-Path` entries must meet certain conditions for validity (see * the * JAR File Specification for details). Invalid `Class-Path` * entries are ignored. For debugging purposes, ignored entries can be * printed to the console if the * {@systemProperty jdk.net.URLClassPath.showIgnoredClassPathEntries} system * property is set to `true`. * * @return The system `ClassLoader` * * @throws SecurityException * If a security manager is present, and the caller's class loader * is not `null` and is not the same as or an ancestor of the * system class loader, and the caller does not have the * {@link RuntimePermission}`("getClassLoader")` * * @throws IllegalStateException * If invoked recursively during the construction of the class * loader specified by the "`java.system.class.loader`" * property. * * @throws Error * If the system property "`java.system.class.loader`" * is defined but the named class could not be loaded, the * provider class does not define the required constructor, or an * exception is thrown by that constructor when it is invoked. The * underlying cause of the error can be retrieved via the * {@link Throwable#getCause()} method. * * @revised 1.4 * @revised 9 */ static get systemClassLoader(): ClassLoader; /** * Returns a `Package` of the given name that * has been defined by this class loader. * * @param name The package name * * @return The `Package` of the given name that has been defined * by this class loader, or `null` if not found * * @throws NullPointerException * if `name` is `null`. * * @jvms 5.3 Creation and Loading * * @since 9 */ getDefinedPackage(name: string): Package; /** * Returns all of the `Package`s that have been defined by * this class loader. The returned array has no duplicated `Package`s * of the same name. * * @apiNote This method returns an array rather than a `Set` or `Stream` * for consistency with the existing {@link #getPackages} method. * * @return The array of `Package` objects that have been defined by * this class loader; or an zero length array if no package has been * defined by this class loader. * * @jvms 5.3 Creation and Loading * * @since 9 */ get definedPackages(): Package[]; /** * Sets the default assertion status for this class loader. This setting * determines whether classes loaded by this class loader and initialized * in the future will have assertions enabled or disabled by default. * This setting may be overridden on a per-package or per-class basis by * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link * #setClassAssertionStatus(String, boolean)}. * * @param enabled * `true` if classes loaded by this class loader will * henceforth have assertions enabled by default, `false` * if they will have assertions disabled by default. * * @since 1.4 */ setDefaultAssertionStatus(enabled: boolean): void; /** * Sets the package default assertion status for the named package. The * package default assertion status determines the assertion status for * classes initialized in the future that belong to the named package or * any of its "subpackages". * * A subpackage of a package named p is any package whose name begins * with "`p.`". For example, `javax.swing.text` is a * subpackage of `javax.swing`, and both `java.util` and * `java.lang.reflect` are subpackages of `java`. * * In the event that multiple package defaults apply to a given class, * the package default pertaining to the most specific package takes * precedence over the others. For example, if `javax.lang` and * `javax.lang.reflect` both have package defaults associated with * them, the latter package default applies to classes in * `javax.lang.reflect`. * * Package defaults take precedence over the class loader's default * assertion status, and may be overridden on a per-class basis by invoking * {@link #setClassAssertionStatus(String, boolean)}. * * @param packageName * The name of the package whose package default assertion status * is to be set. A `null` value indicates the unnamed * package that is "current" * (see section {@jls 7.4.2} of * The Java Language Specification.) * * @param enabled * `true` if classes loaded by this classloader and * belonging to the named package or any of its subpackages will * have assertions enabled by default, `false` if they will * have assertions disabled by default. * * @since 1.4 */ setPackageAssertionStatus(packageName: string, enabled: boolean): void; /** * Sets the desired assertion status for the named top-level class in this * class loader and any nested classes contained therein. This setting * takes precedence over the class loader's default assertion status, and * over any applicable per-package default. This method has no effect if * the named class has already been initialized. (Once a class is * initialized, its assertion status cannot change.) * * If the named class is not a top-level class, this invocation will * have no effect on the actual assertion status of any class. * * @param className * The fully qualified class name of the top-level class whose * assertion status is to be set. * * @param enabled * `true` if the named class is to have assertions * enabled when (and if) it is initialized, `false` if the * class is to have assertions disabled. * * @since 1.4 */ setClassAssertionStatus(className: string, enabled: boolean): void; /** * Sets the default assertion status for this class loader to * `false` and discards any package defaults or class assertion * status settings associated with the class loader. This method is * provided so that class loaders can be made to ignore any command line or * persistent assertion status settings and "start with a clean slate." * * @since 1.4 */ clearAssertionStatus(): void; } /** * Thrown when a stack overflow occurs because an application * recurses too deeply. * * @since 1.0 */ export class StackOverflowError extends VirtualMachineError { /** * Constructs a `StackOverflowError` with no detail message. */ constructor(); /** * Constructs a `StackOverflowError` with the specified * detail message. * * @param s the detail message. */ constructor(s: string); } /** * A stack walker. * * The {@link StackWalker#walk walk} method opens a sequential stream * of {@link StackFrame StackFrame}s for the current thread and then applies * the given function to walk the `StackFrame` stream. * The stream reports stack frame elements in order, from the top most frame * that represents the execution point at which the stack was generated to * the bottom most frame. * The `StackFrame` stream is closed when the `walk` method returns. * If an attempt is made to reuse the closed stream, * `IllegalStateException` will be thrown. * * The {@linkplain Option stack walking options} of a * `StackWalker` determines the information of * {@link StackFrame StackFrame} objects to be returned. * By default, stack frames of the reflection API and implementation * classes are {@linkplain Option#SHOW_HIDDEN_FRAMES hidden} * and `StackFrame`s have the class name and method name * available but not the {@link StackFrame#getDeclaringClass() Class reference}. * * `StackWalker` is thread-safe. Multiple threads can share * a single `StackWalker` object to traverse its own stack. * A permission check is performed when a `StackWalker` is created, * according to the options it requests. * No further permission check is done at stack walking time. * * @apiNote * Examples * * 1. To find the first caller filtering a known list of implementation class: * {@code * StackWalker walker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE); * Optional> callerClass = walker.walk(s -> * s.map(StackFrame::getDeclaringClass) * .filter(interestingClasses::contains) * .findFirst()); * } * * 2. To snapshot the top 10 stack frames of the current thread, * {@code * List stack = StackWalker.getInstance().walk(s -> * s.limit(10).collect(Collectors.toList())); * } * * Unless otherwise noted, passing a `null` argument to a * constructor or method in this `StackWalker` class * will cause a {@link NullPointerException NullPointerException} * to be thrown. * * @since 9 */ export class StackWalker { /** * Returns a `StackWalker` instance. * * This `StackWalker` is configured to skip all * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. * * @return a `StackWalker` configured to skip all * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. * */ static get instance(): StackWalker; /** * Returns a `StackWalker` instance with the given option specifying * the stack frame information it can access. * * * If a security manager is present and the given `option` is * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE}, * it calls its {@link SecurityManager#checkPermission checkPermission} * method for `RuntimePermission("getStackWalkerWithClassReference")`. * * @param option {@link Option stack walking option} * * @return a `StackWalker` configured with the given option * * @throws SecurityException if a security manager exists and its * `checkPermission` method denies access. */ static getInstance(option: Option): StackWalker; /** * Returns a `StackWalker` instance with the given `options` specifying * the stack frame information it can access. If the given `options` * is empty, this `StackWalker` is configured to skip all * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. * * * If a security manager is present and the given `options` contains * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE}, * it calls its {@link SecurityManager#checkPermission checkPermission} * method for `RuntimePermission("getStackWalkerWithClassReference")`. * * @param options {@link Option stack walking option} * * @return a `StackWalker` configured with the given options * * @throws SecurityException if a security manager exists and its * `checkPermission` method denies access. */ static getInstance(options: Set