java-bridge
    Preparing search index...

    Function importClass

    • Import a class. Returns the constructor of the class to be created. For example, import "java.util.ArrayList" for a java Array List.

      Define a custom class type for the imported class and pass the constructor type of the class as the template parameter to get the proper type returned. You could also just cast the result.

      When passing a ClassConfiguration object, the config will be applied to this class. This config does not apply to any other class. If you want to change the config for all classes, use the config class in order to do that. Any undefined field in the config will be ignored and the default value will be used. If you want to change the sync and async suffixes to an empty string, you can pass an empty string as the suffix.

      import { importClass } from 'java-bridge';

      // Import java.util.ArrayList
      const ArrayList = importClass('java.util.ArrayList');

      // Create a new instance of ArrayList
      const list = new ArrayList();
      import { importClass, JavaClass, JavaType } from 'java-bridge';

      // Definitions for class java.util.List
      declare class List<T extends JavaType> extends JavaClass {
      size(): Promise<number>;
      sizeSync(): number;
      add(e: T): Promise<void>;
      addSync(e: T): void;
      get(index: number): Promise<T>;
      getSync(index: number): T;
      toArray(): Promise<T[]>;
      toArraySync(): T[];
      isEmpty(): Promise<boolean>;
      isEmptySync(): boolean;
      }

      // Definitions for class java.util.ArrayList
      declare class ArrayListClass<T extends JavaType> extends List<T> {
      public constructor(other: ArrayListClass<T>);
      public constructor();
      }

      // This causes the class to be imported when the module is loaded.
      class ArrayList<T> extends importClass<typeof ArrayListClass>('java.util.ArrayList')<T> {}

      // Create a new ArrayList instance
      const list = new ArrayList<string>();

      // Add some contents to the list
      list.add('Hello');
      list.add('World');

      // Check the list contents
      assert.equals(list.sizeSync(), 2);
      assert.equals(list.getSync(0), 'Hello');
      assert.equals(list.getSync(1), 'World');
      import { importClass, config } from 'java-bridge';

      // Import java.util.ArrayList with custom config
      const ArrayList = importClass('java.util.ArrayList', {
      syncSuffix: '',
      asyncSuffix: 'Async',
      });

      // Create a new instance of ArrayList
      const list = new ArrayList();

      // Call the async method
      await list.addAsync('Hello World!');

      // Call the sync method
      list.add('Hello World!');

      Type Parameters

      Parameters

      • classname: string

        the name of the class to resolve

      • Optionalconfig: ClassConfiguration

        the config to use when importing the class

      Returns T

      the java class constructor