# Reflection

`com.jsmacrosce.jsmacros.core.library.impl.FReflection`

**Since:** 1.2.3

Loads classes and uses Java reflection through the script global `Reflection`.  
 Minecraft class and member names depend on the loader, runtime mappings, and Minecraft target;  
 they are not universally intermediary names. Primary class lookup uses this library's loader,  
 including jars added with [loadJarFile(String)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_loadJarFile-String-). The two-name [getClass(String, String)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getClass-String-String-)
 overload uses the default loader for its fallback. Legacy `xyz.wagyourtail.` names are
 rewritten before lookup.  
 
 Returned classes, methods and fields are ordinary Java reflection objects. Names absent from
 the shipped TypeScript package model are typed as `unknown`; raw Minecraft members are
 not modeled by those typings. Resolve methods separately from invoking them, for example with
 [invokeMethod(Method, Object, Object...)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_invokeMethod-Method-Object-Object[]-).  
 ```js
// Resolve and construct a JDK class, then look up and invoke a method separately.  
const ArrayList = Reflection.getClass("java.util.ArrayList");  
const list = Reflection.newInstance(ArrayList);  
list.add("diamond");  
const size = Reflection.getDeclaredMethod(ArrayList, "size");  
print(`the list holds ${Reflection.invokeMethod(size, list)}`);  
 ```

 A declared-field lookup can find non-public fields, but reading one requires access and may be
 denied by Java access restrictions.

Accessible in scripts via the global `Reflection` variable.

## Nested types

- [CombinedVariableClassLoader](FReflection.CombinedVariableClassLoader.md)

## Fields

### classLoader {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_classLoader}

```js
static classLoader: FReflection.CombinedVariableClassLoader
```

Shared loader used by [getClass(String)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getClass-String-) and [loadJarFile(String)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_loadJarFile-String-).

## Methods

### compileJavaClass {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_compileJavaClass-String-String-}

```js
compileJavaClass(String className, String code): Class<?>
```

Compiles source into a runtime class and keeps each compilation under the requested name.  
 Each call creates a distinct class; previously returned classes and their instances are
 unaffected. Use the returned [Class](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Class.html) reference to construct instances or store them
 with [FGlobalVars.putObject(String, Object)](FGlobalVars.md#com.jsmacrosce.jsmacros.core.library.impl.FGlobalVars_putObject-String-Object-). A JDK is required to compile classes.  
 ```js
// Recompiling the same name creates a separate class.  
const first = Reflection.compileJavaClass("com.example.Counter",  
  "package com.example; public class Counter { public int n = 0; }");  
const second = Reflection.compileJavaClass("com.example.Counter",  
  "package com.example; public class Counter { public int n = 100; }");  
const versions = Reflection.getAllCompiledJavaClassVersions("com.example.Counter");  
print(`that name now has ${versions.size()} compiled versions`);  

// Keep the class reference to choose which version to instantiate.  
const instance = Reflection.newInstance(first);  
GlobalVars.putObject("counter", instance);  
// getCompiledJavaClass gives the most recent compilation of that name
print(`and the newest is the second one: ${Reflection.getCompiledJavaClass("com.example.Counter") === second}`);  
 ```

**Parameters:**
- `className`: the fully qualified name of the class, including the package
- `code`: the java code to compile

**Returns:** the newly compiled class

**Since:** 1.8.4

### createClassBuilder {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_createClassBuilder-String-Class-Class[]-}

```js
createClassBuilder(String cName, Class<T> clazz, Class<?>... interfaces): ClassBuilder<T>
```

**Parameters:**
- `cName`: generated class name
- `clazz`: superclass
- `interfaces`: interfaces implemented by the generated class

**Type Parameters:**
- `T`: superclass type

**Returns:** the class builder

**Since:** 1.6.5

### createClassProxyBuilder {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_createClassProxyBuilder-Class-Class[]-}

```js
createClassProxyBuilder(Class<T> clazz, Class<?>... interfaces): ProxyBuilder<T>
```

Creates a builder for a guest-language proxy implementing the requested interfaces.

**Parameters:**
- `clazz`: superclass to proxy
- `interfaces`: interfaces implemented by the proxy

**Type Parameters:**
- `T`: superclass type

**Returns:** the proxy builder

**Since:** 1.6.0

### createLibrary {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_createLibrary-String-String-}

```js
createLibrary(String className, String javaCode): void
```

Compiles Java source as a class and registers it as a library. The class must carry a
 [Library](../../../../../../../classes/com/jsmacrosce/jsmacros/core/library/Library.md) annotation and extend [BaseLibrary](../../../../../../../classes/com/jsmacrosce/jsmacros/core/library/BaseLibrary.md) (directly or through a supported
 per-exec or per-language base class).

**Parameters:**
- `className`: the fully qualified name of the class, including the package
- `javaCode`: the source code of the library

**Since:** 1.8.4

### createLibraryBuilder {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_createLibraryBuilder-String-boolean-String[]-}

```js
createLibraryBuilder(String name, boolean perExec, String... acceptedLangs): LibraryBuilder
```

Creates a builder for a runtime-generated library class, configured with its script global,  
 lifecycle, and supported languages. The generated class is registered for scripts only when
 [LibraryBuilder.finishBuildAndFreeze()](../../../../../../../classes/com/jsmacrosce/jsmacros/core/library/impl/classes/LibraryBuilder.md#com.jsmacrosce.jsmacros.core.library.impl.classes.LibraryBuilder_finishBuildAndFreeze-) is called.  
 [LibraryBuilder.addConstructor()](../../../../../../../classes/com/jsmacrosce/jsmacros/core/library/impl/classes/LibraryBuilder.md#com.jsmacrosce.jsmacros.core.library.impl.classes.LibraryBuilder_addConstructor-) adds a public constructor whose parameters are
 determined by this builder's lifecycle and language configuration; if omitted, the builder
 supplies a forwarding constructor automatically.

**Parameters:**
- `name`: name of the script global
- `perExec`: whether to create a library per script run rather than per profile
- `acceptedLangs`: guest languages allowed to use the library; empty means all

**Returns:** a builder for assembling the library class

### getAllCompiledJavaClassVersions {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getAllCompiledJavaClassVersions-String-}

```js
getAllCompiledJavaClassVersions(String className): List<Class<?>>
```

Returns the compiled classes cached under the requested name, in compilation order.

**Parameters:**
- `className`: the fully qualified class name

**Returns:** an immutable snapshot of compiled classes in compilation order, or an empty list if none are cached

**Since:** 1.8.4

### getClass {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getClass-String-}

```js
getClass(String name): Class<T>
```

Resolves a fully qualified class name through this library's loader, including jars added
 by [loadJarFile(String)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_loadJarFile-String-), and initializes the class. The nine lower-case Java
 primitive names, including `void`, resolve directly to their primitive classes.  
 The legacy `xyz.wagyourtail.` package prefix is rewritten before loading.  
 Returns an ordinary [Class](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Class.html); use [getClass(String, String)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getClass-String-String-) for an alternative
 name when the first is absent. Minecraft class names depend on the runtime mappings.

**Parameters:**
- `name`: name of class like `path.to.class`

**Type Parameters:**
- `T`: type represented by the resolved class

**Returns:** resolved class

**Since:** 1.2.3

### getClass {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getClass-String-String-}

```js
getClass(String name, String name2): Class<T>
```

Tries the first class name, then the second only if the first lookup throws
 [ClassNotFoundException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/ClassNotFoundException.html). This can accommodate differing runtime mappings when the
 supplied names match them; it does not guarantee that either name exists on every version.  
 The second lookup uses the default class loader, not this library's loader, so it does not
 use jars registered only through [loadJarFile(String)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_loadJarFile-String-). A primitive first name resolves directly and
 does not fall back; a successfully resolved but unintended class also prevents fallback.  
 ```js
// Put the runtime's expected name first; the alternative is tried only if it is absent.  
const List = Reflection.getClass("example.Missing", "java.util.ArrayList");  
const list = Reflection.newInstance(List);  
list.add("item");  
 ```

**Parameters:**
- `name`: first try
- `name2`: second try

**Type Parameters:**
- `T`: type represented by the resolved class

**Returns:** a [Class](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Class.html) reference.

**Since:** 1.2.3

### getClass {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getClass-}

```js
getClass(): Class<?>
```

**Returns:** `Class<?>`

### getClassFromClassBuilderResult {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getClassFromClassBuilderResult-String-}

```js
getClassFromClassBuilderResult(String cName): Class<?>
```

**Parameters:**
- `cName`: generated class name used to create the class

**Returns:** the generated class

**Since:** 1.6.5

### getClassName {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getClassName-Object-}

```js
getClassName(Object o): String
```

Returns the canonical name of a class or an object's runtime class. Canonical names use dots
 for nested classes; the result is `null` for local and anonymous classes. Arrays and
 primitive classes use their canonical names.  
 ```js
const ArrayList = Reflection.getClass("java.util.ArrayList");  
// a Class names itself, whatever the instance it came from was
print(`the class is ${Reflection.getClassName(ArrayList)}`);  
// an instance names its runtime type, which is the subclass
print(`the instance is ${Reflection.getClassName(Reflection.newInstance(ArrayList))}`);  
// a primitive class names the primitive
print(`and a primitive is ${Reflection.getClassName(Reflection.getClass("int"))}`);  
 ```

**Parameters:**
- `o`: a [Class](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Class.html) or an object whose runtime class should be named

**Returns:** the canonical class name, or `null` if it has none

**Since:** 1.3.1

### getCompiledJavaClass {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getCompiledJavaClass-String-}

```js
getCompiledJavaClass(String className): Class<?>
```

Returns the most recently compiled class cached under the requested name.

**Parameters:**
- `className`: the fully qualified class name

**Returns:** the most recently compiled class, or `null` if none is cached

**Since:** 1.8.4

### getDeclaredField {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getDeclaredField-Class-String-}

```js
getDeclaredField(Class<?> c, String name): Field
```

Finds a field declared directly by the class, including non-public fields.

**Parameters:**
- `c`: class to search
- `name`: field name

**Returns:** the declared field

**Since:** 1.2.3

**See:**
- [FReflection.getDeclaredField(Class, String, String)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getDeclaredField-Class-String-String-)

### getDeclaredField {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getDeclaredField-Class-String-String-}

```js
getDeclaredField(Class<?> c, String name, String name2): Field
```

Finds a declared field by trying `name`, then `name2` if the first lookup throws
 [NoSuchFieldException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/NoSuchFieldException.html) or [SecurityException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/SecurityException.html).

**Parameters:**
- `c`: class declaring the field
- `name`: primary field name
- `name2`: fallback field name

**Returns:** the matching field

**Since:** 1.2.3

### getDeclaredMethod {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getDeclaredMethod-Class-String-Class[]-}

```js
getDeclaredMethod(Class<?> c, String name, Class<?>... parameterTypes): Method
```

Finds a method declared directly by the class, matching its exact parameter classes; it
 does not find inherited methods. Use [getMethod(Class, String, Class...)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getMethod-Class-String-Class[]-) for public
 methods including inherited ones. The two-name [getDeclaredMethod(Class, String, String, Class...)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getDeclaredMethod-Class-String-String-Class[]-)
 overload retries with another method name. The returned [Method](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/reflect/Method.html) must be
 invoked separately with [invokeMethod(Method, Object, Object...)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_invokeMethod-Method-Object-Object[]-). Non-public
 methods may require `setAccessible(true)`, subject to Java access restrictions.  
 ```js
const StringClass = Reflection.getClass("java.lang.String");  
const startsWith = Reflection.getDeclaredMethod(
  StringClass, "startsWith", StringClass);  
print(Reflection.invokeMethod(startsWith, "hello", "he"));  
 ```

**Parameters:**
- `c`: the class to look the method up on
- `name`: the method's name
- `parameterTypes`: the exact classes of the method's parameters, none for no parameters

**Returns:** the method, which has to be invoked separately

**Since:** 1.2.3

### getDeclaredMethod {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getDeclaredMethod-Class-String-String-Class[]-}

```js
getDeclaredMethod(Class<?> c, String name, String name2, Class<?>... parameterTypes): Method
```

Finds a declared method by trying `name`, then `name2` if lookup by the first
 name throws [NoSuchMethodException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/NoSuchMethodException.html) or [SecurityException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/SecurityException.html). Both names use the
 same exact parameter types.

**Parameters:**
- `c`: class declaring the method
- `name`: primary method name
- `name2`: fallback method name
- `parameterTypes`: exact parameter types

**Returns:** the matching method

**Since:** 1.2.3

### getField {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getField-Class-String-}

```js
getField(Class<?> c, String name): Field
```

Finds a public field by name.

**Parameters:**
- `c`: class to search
- `name`: field name

**Returns:** the matching public field

**Since:** 1.6.0

### getField {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getField-Class-String-String-}

```js
getField(Class<?> c, String name, String name2): Field
```

Returns a public field, trying `name2` if lookup by `name` throws
 [NoSuchFieldException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/NoSuchFieldException.html) or [SecurityException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/SecurityException.html).

**Parameters:**
- `c`: class to search
- `name`: primary field name
- `name2`: fallback field name

**Returns:** the matching public field

**Since:** 1.6.0

### getMethod {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getMethod-Class-String-String-Class[]-}

```js
getMethod(Class<?> c, String name, String name2, Class<?>... parameterTypes): Method
```

Finds a public method by trying `name`, then `name2` if the first lookup throws
 [NoSuchMethodException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/NoSuchMethodException.html) or [SecurityException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/SecurityException.html).

**Parameters:**
- `c`: class to search
- `name`: primary method name
- `name2`: fallback method name
- `parameterTypes`: exact parameter types

**Returns:** the matching public method

**Since:** 1.6.0

### getMethod {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getMethod-Class-String-Class[]-}

```js
getMethod(Class<?> c, String name, Class<?>... parameterTypes): Method
```

Finds a public method by name and exact parameter types.

**Parameters:**
- `c`: class to search
- `name`: method name
- `parameterTypes`: exact parameter types

**Returns:** the matching public method

**Since:** 1.6.0

### getReflect {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getReflect-Object-}

```js
getReflect(Object obj): Reflect
```

Returns a jOOR reflection wrapper for the object. Wrapper operations can be chained; fields
 are made accessible when reached. Unlike this library's invocation helpers, the wrapper does
 not coerce numeric arguments.  
 ```js
const stack = Client.getRegistryManager().getItemStack("minecraft:diamond");  
const reflected = Reflection.getReflect(stack.getRaw());  
print(`calling through it: ${reflected.call("getCount")}`);  
print(`the private count field says ${reflected.field("count").get()}`);  
 ```

**Parameters:**
- `obj`: the object to wrap

**Returns:** a reflection wrapper for the object

**Since:** 1.8.4

### invokeMethod {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_invokeMethod-Method-Object-Object[]-}

```js
invokeMethod(Method m, Object c, Object... objects): Object
```

Invokes a method, coercing each numeric argument to the corresponding parameter type.  
 Non-numeric arguments are passed through. Pass `null` as the receiver for a static
 method. The underlying reflective invocation enforces access and wraps target exceptions in
 [InvocationTargetException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/reflect/InvocationTargetException.html).  
 ```js
// a number out of a script is a double, and the coercion makes it fit an int
// parameter anyway. a null receiver means a static method
const Integer = Reflection.getClass("java.lang.Integer");  
const bitCount = Reflection.getDeclaredMethod(Integer, "bitCount",  
  Reflection.getClass("int"));  
print(`the bit count of 3 is ${Reflection.invokeMethod(bitCount, null, 3)}`);  

// anything that is not a number is passed through untouched
const ArrayList = Reflection.getClass("java.util.ArrayList");  
const list = Reflection.newInstance(ArrayList);  
const add = Reflection.getDeclaredMethod(ArrayList, "add",  
  Reflection.getClass("java.lang.Object"));  
Reflection.invokeMethod(add, list, "diamond");  
print(`the list holds ${list.size()}`);  
 ```

**Parameters:**
- `m`: method to invoke
- `c`: receiver, or `null` for a static method
- `objects`: invocation arguments

**Returns:** the method result, or `null` for a `void` method

**Since:** 1.2.3

### loadJarFile {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_loadJarFile-String-}

```js
loadJarFile(String file): boolean
```

Adds a jar from the script's folder to this library's class loader. Its classes can then be
 resolved through [getClass(String)](#com.jsmacrosce.jsmacros.core.library.impl.FReflection_getClass-String-) and compilation using that loader. Loading an
 already-added jar returns `true`; a missing path throws [FileNotFoundException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/io/FileNotFoundException.html).  
 ```js
const first = Reflection.loadJarFile("libs/mylib.jar");  
const second = Reflection.loadJarFile("libs/mylib.jar");  
print(`loaded ${first}, and again ${second}`);  

const MyThing = Reflection.getClass("com.example.MyThing");  
print(`that is ${Reflection.getClassName(MyThing)}`);  
 ```

**Parameters:**
- `file`: path to the jar, resolved relative to the script's folder

**Returns:** `true` if the jar was added or was already loaded

**Since:** 1.2.6

### newInstance {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_newInstance-Class-Object[]-}

```js
newInstance(Class<T> c, Object... objects): T
```

Creates an instance using a matching public constructor, coercing numeric arguments if needed.  
 A `null` argument causes a [NullPointerException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/NullPointerException.html) before constructor lookup.

**Parameters:**
- `c`: class to instantiate
- `objects`: constructor arguments

**Type Parameters:**
- `T`: type of instance to construct

**Returns:** the constructed instance

**Since:** 1.2.7

### newInstance0 {#com.jsmacrosce.jsmacros.core.library.impl.FReflection_newInstance0-Class-Object[]-}

```js
static newInstance0(Class<T> c, Object... objects): T
```

Constructs an instance using a public constructor with exactly matching runtime parameter
 types, or tries public constructors of the same arity with numeric arguments coerced to their
 parameter types. If no attempt succeeds, throws a [RuntimeException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/RuntimeException.html).

**Parameters:**
- `c`: the class to construct
- `objects`: constructor arguments

**Type Parameters:**
- `T`: type of instance to construct

**Returns:** the constructed instance
