### Start JVM and Use Java String Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt A complete example demonstrating how to start the Java Virtual Machine (JVM) with JPype, import a Java class, and use its methods. The classpath can be specified to include custom JARs or class directories. ```python import jpype import jpype.imports # Start the JVM jpype.startJVM(classpath=["../jar/*","../classes","com.amce-1.0.jar"]) # Import Java classes from java.lang import String # Use the Java String class java_string = String("Hello from Java!") print(java_string.toUpperCase()) # Output: HELLO FROM JAVA! ``` -------------------------------- ### Start JVM Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Initialize the Java Virtual Machine (JVM) using JPype. This is a prerequisite for any Java interaction. An empty classpath is provided in this example. ```python import jpype # Start the JVM jpype.startJVM(classpath=[]) ``` -------------------------------- ### Start JVM with Memory and GC Options Source: https://jpype.readthedocs.io/en/latest/userguide.html Customize JVM startup using the `jvmOptions` argument in `startJVM()`. This example sets the maximum heap size to 512MB and enables the G1 garbage collector. ```python jpype.startJVM(jvmOptions=["-Xmx512m", "-XX:+UseG1GC"]) ``` -------------------------------- ### Start JPype JVM and Import Java Types Source: https://jpype.readthedocs.io/en/latest/userguide.html This snippet shows the basic setup for using JPype. It imports the necessary modules, makes standard Java types available, and starts the Java Virtual Machine. ```python # Import the module import jpype # Allow Java modules to be imported import jpype.imports # Import all standard Java types into the global scope from jpype.types import * # Import each of the decorators into the global scope from jpype import JImplements, JOverride, JImplementationFor # Start JVM with Java types on return jpype.startJVM() ``` -------------------------------- ### Start JVM with Initializer Functions Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Provide a list of Python functions to be executed during JVM startup using the `initializers` argument. This allows for custom setup logic before the JVM is fully operational. ```python jpype.startJVM(initializers=[setup]) ``` -------------------------------- ### Start JVM with Classpath Specification Source: https://jpype.readthedocs.io/en/latest/userguide.html Specify paths to JAR files and Java classes using the `classpath` argument in `startJVM()`. This example includes all JARs in the 'lib/' directory and the 'classes' directory. ```python jpype.startJVM(classpath=["lib/*", "classes"]) ``` -------------------------------- ### Start JVM with JDK Documentation Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Starts the Java Virtual Machine with the JDK documentation zip file on the classpath to enable access to javadoc. ```java import jpype lpjpype.startJVM(classpath='jdk-11.0.7_doc-all.zip') ``` -------------------------------- ### Start JVM with Default Settings Source: https://jpype.readthedocs.io/en/latest/api.html Starts the Java Virtual Machine using default classpath and jvmpath. Use this for basic JVM initialization. ```python jpype.startJVM() ``` -------------------------------- ### Start JVM with Classpath and Options Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt This snippet demonstrates how to start the JVM, specifying the classpath for Java classes and enabling assertions using JVM options. ```python import jpype # Start the JVM with classpath and options jpype.startJVM( classpath=['lib/*', 'classes'], jvmOptions=["-ea"] # Enable assertions ) ``` -------------------------------- ### Complete First JPype Program Source: https://jpype.readthedocs.io/en/latest/userguide.html A full example demonstrating starting the JVM with a specified classpath, importing a Java class, and using its methods. The JVM termination is handled automatically when the Python script exits. ```python import jpype import jpype.imports # Start the JVM jpype.startJVM(classpath=["../jar/*","../classes","com.amce-1.0.jar"]) # Import Java classes from java.lang import String # Use the Java String class java_string = String("Hello from Java!") print(java_string.toUpperCase()) # Output: HELLO FROM JAVA! ``` -------------------------------- ### Run JPype Example Script Source: https://jpype.readthedocs.io/en/latest/userguide.html Execute the Python script containing the JPype example. ```bash python hello_jpype.py ``` -------------------------------- ### Start JVM with Default Packages Source: https://jpype.readthedocs.io/en/latest/userguide.html Imports default Java packages and starts the Java Virtual Machine. This is a common starting point for JPype applications. ```python import java.lang import java.util ``` -------------------------------- ### Install Built JPype Wheel Source: https://jpype.readthedocs.io/en/latest/_sources/install.rst.txt Install a pre-built JPype wheel file after compiling the source. This command is used to install the artifact produced by the build process. ```bash pip install /path/to/wheel ``` -------------------------------- ### Start JVM with JAR and Javadoc Classpath Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Starts the JVM with both a JAR file and its corresponding javadoc JAR on the classpath, allowing for documentation extraction. ```java import jpype lpjpype.startJVM(classpath=['gson-2.8.5.jar', 'gson-2.8.5-javadoc.jar']) ``` -------------------------------- ### Install Build Tools on Debian/Ubuntu Source: https://jpype.readthedocs.io/en/latest/install.html Install necessary build tools, g++ and python-dev, on Debian/Ubuntu systems for compiling CPython modules. ```bash sudo apt-get install g++ python3-dev ``` -------------------------------- ### Start JVM with Custom Arguments Source: https://jpype.readthedocs.io/en/latest/api.html Starts the Java Virtual Machine with specified JVM arguments, custom jvmpath, and classpath. Useful for configuring the JVM environment. ```python jpype.startJVM("jvmpath", classpath="/path/to/your/classes.jar") ``` -------------------------------- ### Java Example Code Source: https://jpype.readthedocs.io/en/latest/userguide.html This is an example of Java code for database interaction. It shows how to establish a connection, run a query, and process records. ```java package com.paying.customer; import com.paying.customer.DataBase public class MyExample { public void main(String[] args) { Database db = new Database("our_records"); try (DatabaseConnection c = db.connect()) { c.runQuery(); while (c.hasRecords()) { Record record = db.nextRecord(); ... } } } } ``` -------------------------------- ### Install JPype using Pip Source: https://jpype.readthedocs.io/en/latest/_sources/install.rst.txt Install the latest version of JPype from PyPI using pip. This command attempts to install from a binary distribution if available, otherwise it builds from source. ```bash pip install JPype1 ``` -------------------------------- ### Start JVM and Load Java Object Source: https://jpype.readthedocs.io/en/latest/userguide.html Boilerplate code to start the Java Virtual Machine and load a serialized Java object from a file. Ensure 'myobject.ser' exists in the same directory. ```python import jpype import jpype.imports jpype.startJVM(classpath = ['jars/*', 'test/classes']) from java.nio.file import Files, Paths from java.io import ObjectInputStream with Files.newInputStream(Paths.get("myobject.ser")) as stream: ois = ObjectInputStream(stream) obj = ois.readObject() print(obj) # prints org.bigstuff.MyObject@7382f612 ``` -------------------------------- ### Start JVM with Autopep8 Ignore Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Starts the JVM and imports Java classes, demonstrating the correct order of operations when using Autopep8 with the '--ignore E402' flag. ```python import jpype import jpype.imports lpjpype.startJVM() from gov.llnl.math import DoubleArray ``` -------------------------------- ### Install Debian/Ubuntu Development Packages Source: https://jpype.readthedocs.io/en/latest/_sources/install.rst.txt Install necessary development packages for building CPython modules on Debian/Ubuntu systems, including g++ and python3-dev. ```bash sudo apt-get install g++ python3-dev ``` -------------------------------- ### Start JVM with Ignore Unrecognized Arguments Source: https://jpype.readthedocs.io/en/latest/api.html Starts the JVM, ignoring any unrecognized JVM arguments. This is helpful when dealing with potentially incompatible JVM flags. ```python jpype.startJVM(ignoreUnrecognized=True) ``` -------------------------------- ### Enable Coverage with setup.py Source: https://jpype.readthedocs.io/en/latest/_sources/develguide.rst.txt Additional instrumentation for running some tests can be enabled using the '--enable-coverage' option during development setup. ```bash python setup.py develop --enable-coverage ``` -------------------------------- ### Install Latest JPype using Pip Source: https://jpype.readthedocs.io/en/latest/install.html Install the latest stable version of JPype from PyPI using pip. This command will install from either a source or binary distribution. ```bash pip install JPype1 ``` -------------------------------- ### Start JVM with Remote Debugging Options Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Starts the Java Virtual Machine with options to enable remote debugging, allowing a Java debugger to attach. ```python jpype.startJVM("-Xint", "-Xdebug", "-Xnoagent", "-Xrunjdwp:transport=dt_socket,server=y,address=12999,suspend=n") ``` -------------------------------- ### Start JVM with Namespace Import Source: https://jpype.readthedocs.io/en/latest/userguide.html Starts the Java Virtual Machine using a namespace import for the JPype module. This style avoids cluttering the global scope with JPype-specific names. ```python import jpype as jp jp.startJVM() ``` -------------------------------- ### jpype.startJVM Source: https://jpype.readthedocs.io/en/latest/api.html Starts a Java Virtual Machine. This function can be used to initialize the JVM with custom arguments, classpath, and other configurations. ```APIDOC ## jpype.startJVM ### Description Starts a Java Virtual Machine. Without options it will start the JVM with the default classpath and jvmpath. The default classpath is determined by `jpype.getClassPath()`. The default jvmpath is determined by `jpype.getDefaultJVMPath()`. ### Method `jpype.startJVM(_* jvmargs: str_, _jvmpath : Optional[_PathOrStr] = None_, _classpath : Union[Sequence[_PathOrStr], _PathOrStr, None] = None_, _ignoreUnrecognized : bool = False_, _convertStrings : bool = False_, _interrupt : bool = True_, _minimum_version : Optional[str] = None_) → None` ### Parameters #### Positional Arguments * **jvmargs** (_Optional[str]_) – Arguments to give to the JVM. The first argument may be the path to the JVM. #### Keyword Arguments * **jvmpath** (_Optional[Union[str, _PathOrStr]]_) – Path to the jvm library file, Typically one of (`libjvm.so`, `jvm.dll`, …) Using None will apply the default jvmpath. * **classpath** (_Optional[Union[Sequence[_PathOrStr], _PathOrStr]]_) – Set the classpath for the JVM. This will override any classpath supplied in the arguments list. A value of None will give no classpath to JVM. * **ignoreUnrecognized** (_bool_) – Option to ignore invalid JVM arguments. Default is False. * **convertStrings** (_bool_) – Option to force Java strings to cast to Python strings. This option is to support legacy code for which conversion of Python strings was the default. This will globally change the behavior of all calls using strings, and a value of True is NOT recommended for newly developed code. * **interrupt** (_bool_) – Option to install ^C signal handlers. If True then ^C will stop the process, else ^C will transfer control to Python rather than halting. If not specified will be False if Python is started as an interactive shell. ### Raises * **OSError** – if the JVM cannot be started or is already running. * **TypeError** – if a keyword argument conflicts with the positional arguments. ``` -------------------------------- ### Install Built JPype Wheel Source: https://jpype.readthedocs.io/en/latest/install.html Install a previously built JPype wheel package using pip. This command is used after building the wheel manually. ```bash pip install /path/to/wheel ``` -------------------------------- ### Install JPype from GitHub using Pip Source: https://jpype.readthedocs.io/en/latest/_sources/install.rst.txt Install JPype directly from the GitHub repository using pip. This method requires the Java Development Kit (JDK) as it does not include a prebuilt JAR. ```bash pip install git+https://github.com/jpype-project/jpype.git ``` -------------------------------- ### Start JVM with String Conversion Option Source: https://jpype.readthedocs.io/en/latest/api.html Starts the JVM with an option to force Java strings to cast to Python strings. Note: This is not recommended for new code. ```python jpype.startJVM(convertStrings=True) ``` -------------------------------- ### Build JPype Source with Pip Source: https://jpype.readthedocs.io/en/latest/_sources/install.rst.txt Build and install JPype from source using pip. This command is used when installing from a local source directory or a source distribution. ```bash python -m build /path/to/source ``` -------------------------------- ### jpype.onJVMStart Source: https://jpype.readthedocs.io/en/latest/api.html Decorator to register a function to be called after the JVM is started. Useful for loading module resources that depend on the JVM. ```APIDOC ## @jpype.onJVMStart ### Description Decorator to register a function to be called after JVM is started. This can be used to load module resources that depend on the JVM such as loading classes. If the JVM is not started, the user supplied function is held in a list until the JVM starts. When startJVM is called, all functions on the deferred list are called and the list is cleared. If the JVM is already started, then the function is called immediately. Errors from the function will either be raised immediately if the JVM is started, or from startJVM if the JVM is not yet started. ### Parameters * **func** (_callable_) – a function to call when the JVM is started. ``` -------------------------------- ### Minimalist JPype Initialization Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt A more concise method for initializing JPype, importing the module with an alias and starting the JVM. ```python import jpype as jp # Import the module jp.startJVM() # Start the module ``` -------------------------------- ### Start JPype JVM Source: https://jpype.readthedocs.io/en/latest/quickguide.html Import necessary JPype modules and types, then launch the Java Virtual Machine (JVM) to enable Java-Python interoperability. ```python # Import module import jpype # Enable Java imports import jpype.imports # Pull in types from jpype.types import * # Launch the JVM jpype.startJVM() ``` -------------------------------- ### Filter and Map Java List with Streams Source: https://jpype.readthedocs.io/en/latest/userguide.html Use Java Stream API for filtering and mapping elements in a Java list. This example filters strings starting with 'a' and maps them to uppercase. ```python filtered = jlist.stream().filter(lambda s: s.startswith("a")).map( lambda s: s.upper()).collect(Collectors.toList()) print(filtered) # Output: [APPLE] ``` -------------------------------- ### Enable Tracing with setup.py Source: https://jpype.readthedocs.io/en/latest/_sources/develguide.rst.txt To activate the CPython and C++ layer logger, compile the jpype module with the '--enable-tracing' option. ```bash python setup.py develop --enable-tracing ``` -------------------------------- ### JPype Python Integration Example Source: https://jpype.readthedocs.io/en/latest/userguide.html This Python code uses JPype to interact with Java libraries. It demonstrates starting the JVM, importing Java modules, and calling Java methods. ```python # Boiler plate stuff to start the module import jpype import jpype.imports from jpype.types import * # Launch the JVM jpype.startJVM(classpath=['jars/database.jar']) # import the Java modules from com.paying.customer import DataBase # Copy in the patterns from the guide to replace the example code db = Database("our_records") with db.connect() as c: c.runQuery() while c.hasRecords(): record = db.nextRecord() ... ``` -------------------------------- ### Import Java Packages as Modules Source: https://jpype.readthedocs.io/en/latest/api.html This snippet demonstrates how to import Java packages and classes as Python modules using the JPype Imports module. It requires JPype to be installed and the JVM to be started. ```python import jpype import jpype.imports jpype.startJVM() # Import java packages as modules from java.lang import String ``` -------------------------------- ### Setup GUI Environment with Callback Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Ensures GUI applications run correctly across platforms by setting up the necessary environment, especially for macOS's event loop requirements. It takes a callback function to initialize and launch the GUI. ```python from jpype import setupGuiEnvironment from javafx.application import Platform def say_hello_later(): """Test function for scheduling a task on the JavaFX Application Thread.""" print("Hello from JavaFX!") def launch_gui(): """Launch the GUI application.""" # Example: Schedule a task on the JavaFX Application Thread Platform.runLater(say_hello_later) print("GUI launched") # Use setupGuiEnvironment to ensure cross-platform compatibility setupGuiEnvironment(launch_gui) ``` -------------------------------- ### Filter Java List with Streams and Process with List Comprehension Source: https://jpype.readthedocs.io/en/latest/userguide.html Combines Java Stream API for filtering with Pythonic list comprehension for post-processing. This example filters strings starting with 'a' and then converts them to lowercase. ```python # Use Java Stream API for filtering filtered_stream = jlist.stream().filter(lambda s: s.startswith("a")).collect( Collectors.toList()) # Use Pythonic list comprehension for further processing final_result = [item.lower() for item in filtered_stream] print(final_result) # Output: ['apple'] ``` -------------------------------- ### Creating and Showing a Swing JFrame Source: https://jpype.readthedocs.io/en/latest/userguide.html Illustrates how to create a simple 'Hello World' Swing JFrame and display it using JPype. It requires starting the JVM and importing Java Swing components. ```python import jpype import jpype.imports jpype.startJVM() import java import javax from javax.swing import * def createAndShowGUI(): frame = JFrame("HelloWorldSwing") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) label = JLabel("Hello World") frame.getContentPane().add(label) frame.pack() frame.setVisible(True) # Start an event loop thread to handling gui events @jpype.JImplements(java.lang.Runnable) class Launch: @jpype.JOverride def run(self): createAndShowGUI() javax.swing.SwingUtilities.invokeLater(Launch()) ``` -------------------------------- ### Use Java Object Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Create and manipulate Java objects within a Python script after starting the JVM and importing the necessary classes. This example demonstrates creating a Java String object and calling its toUpperCase method. ```python java_string = String("Hello from Java!") print(java_string.toUpperCase()) # Output: HELLO FROM JAVA! ``` -------------------------------- ### Start JVM with Memory and GC Tuning Options Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Use the `jvmOptions` flag to specify JVM arguments for memory allocation and garbage collection tuning during startup. This is useful for optimizing performance. ```python jpype.startJVM(jvmOptions=["-Xmx512m", "-XX:+UseG1GC"]) ``` -------------------------------- ### Test JPype with Pytest Source: https://jpype.readthedocs.io/en/latest/_sources/install.rst.txt Run the JPype test suite using pytest after installation. This is an optional step to verify the installation. ```bash python -m pytest ``` -------------------------------- ### Get Array Size Source: https://jpype.readthedocs.io/en/latest/_sources/quickguide.rst.txt Shows how to get the size (number of elements) of an array in Java and its Python equivalent using JPype. ```java array.length ``` ```python len(array) ``` -------------------------------- ### Register Function on JVM Start Source: https://jpype.readthedocs.io/en/latest/api.html Decorator to register a function to be called after the JVM is started. Useful for loading resources that depend on the JVM. ```python @jpype.onJVMStart def my_init_function(): pass ``` -------------------------------- ### Java Example for Database Interaction Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt This Java code demonstrates interacting with a database using a custom library. It shows how to establish a connection, run a query, and process records. ```java package com.paying.customer; import com.paying.customer.DataBase public class MyExample { public void main(String[] args) { Database db = new Database("our_records"); try (DatabaseConnection c = db.connect()) { c.runQuery(); while (c.hasRecords()) { Record record = db.nextRecord(); ... } } } } ``` -------------------------------- ### JPype Initialization with Standard Imports Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt This snippet shows the recommended way to import JPype modules, start the JVM, and import standard Java types and decorators for general use. ```python # Import the module import jpype # Allow Java modules to be imported import jpype.imports # Import all standard Java types into the global scope from jpype.types import * # Import each of the decorators into the global scope from jpype import JImplements, JOverride, JImplementationFor # Start JVM with Java types on return jpype.startJVM() # Import default Java packages import java.lang import java.util ``` -------------------------------- ### Creating and Displaying a Swing "Hello World" Frame Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Launches a simple Swing "Hello World" frame from Python. It requires starting the JVM and using SwingUtilities.invokeLater to ensure the GUI events are handled correctly on a user thread. ```python import jpype import jpype.imports jpype.startJVM() import java import javax from javax.swing import * def createAndShowGUI(): frame = JFrame("HelloWorldSwing") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) label = JLabel("Hello World") frame.getContentPane().add(label) frame.pack() frame.setVisible(True) # Start an event loop thread to handling gui events @jpype.JImplements(java.lang.Runnable) class Launch: @jpype.JOverride def run(self): createAndShowGUI() javax.swing.SwingUtilities.invokeLater(Launch()) ``` -------------------------------- ### JProxy Syntax with Dict and Inst Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Illustrates the syntax for creating a JProxy that combines methods from both a dictionary and an object instance. ```python JProxy(interface, dict=my_dict, inst=my_instance) ``` -------------------------------- ### Install JPype using Conda Source: https://jpype.readthedocs.io/en/latest/_sources/install.rst.txt Install JPype from the conda-forge channel using the conda package manager. This is recommended for users with Anaconda or Miniconda. ```bash conda install -c conda-forge jpype1 ``` -------------------------------- ### Verify JPype Installation Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Confirm that JPype has been installed correctly by importing it in a Python script. This snippet checks for successful import and prints a confirmation message. ```python import jpype print("JPype installed successfully!") ``` -------------------------------- ### Running Experiment and Plotting Results Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Demonstrates adding a Python-implemented Java monitor to an experiment, running the experiment, and plotting the collected results. ```python hm = HeartMonitor() experiment.addMoniter(hm) # Corrected typo from addMonitor experiment.run() readings = hm.getResults() plt.plot(readings[:,0], readings[:,1]) plt.show() ``` -------------------------------- ### Define Java Classes for JPype Examples Source: https://jpype.readthedocs.io/en/latest/quickguide.html These Java classes serve as the foundation for JPype examples, showcasing fields, methods, constructors, and exception handling. ```java package org.pkg; public class BaseClass { public void callMember(int i) {} } public class MyClass extends BaseClass { final public static int CONST_FIELD = 1; public static int staticField = 1; public int memberField = 2; int internalField =3; public MyClass() {} public MyClass(int i) {} public static void callStatic(int i) {} public void callMember(int i) {} // Python name conflict public void pass() {} public void throwsException() throws java.lang.Exception {} // Overloaded methods public void call(int i) {} public void call(double d) {} } ``` -------------------------------- ### Start JPype JVM with Classpath Source: https://jpype.readthedocs.io/en/latest/quickguide.html Launch the Java Virtual Machine (JVM) and specify a classpath to include necessary Java Archive (JAR) files. ```python # Launch the JVM jpype.startJVM(classpath = ['jars/*']) ``` -------------------------------- ### Create Initialized Primitive Array in Java Source: https://jpype.readthedocs.io/en/latest/_sources/quickguide.rst.txt Demonstrates how to create and initialize a primitive integer array in Java using JPype. ```java int[] array = new int[]{1,2,3} ``` -------------------------------- ### Create Initialized Boxed Array in Java Source: https://jpype.readthedocs.io/en/latest/_sources/quickguide.rst.txt Demonstrates how to create and initialize a boxed Integer array in Java using JPype. ```java Integer[] array = new Integer[]{1,2,3} ``` -------------------------------- ### Start JVM with Manual Path and Classpath Source: https://jpype.readthedocs.io/en/latest/userguide.html If automatic JVM detection fails, specify the JVM shared library path manually as the first argument to `startJVM()`. The `classpath` argument is used to include JAR files and classes. ```python jpype.startJVM('/path/to/libjvm.so', classpath=['lib/*']) ``` -------------------------------- ### Set JAVA_HOME Environment Variable Source: https://jpype.readthedocs.io/en/latest/_sources/install.rst.txt Explicitly set the JAVA_HOME environment variable to the JDK installation path when running the build process. This is a common fix for installation failures. ```bash JAVA_HOME=/usr/lib/java/jdk1.8.0/ python -m build . ``` -------------------------------- ### Build JPype Wheel using build module Source: https://jpype.readthedocs.io/en/latest/install.html Build a JPype wheel package from source using the 'build' module. This command compiles JPype and prepares it for installation. ```bash python -m build /path/to/source ``` -------------------------------- ### Get Class Path with Environment Source: https://jpype.readthedocs.io/en/latest/api.html Gets the full Java class path, including user-added paths and the environment CLASSPATH. Set env=False to exclude environment variables. ```python jpype.getClassPath() ``` ```python jpype.getClassPath(False) ``` -------------------------------- ### Access Private Field via Reflection Source: https://jpype.readthedocs.io/en/latest/quickguide.html Accesses a private field of a Java object using reflection. Requires getting the field, setting accessibility, and then getting the value. ```python cls = myObject.class_ field = cls.getDeclaredField("internalField") field.setAccessible(True) field.get() ``` -------------------------------- ### Start JVM with Specified Classpath Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Use the `classpath` argument to provide paths to JAR files and Java classes required by your application. This ensures that the JVM can locate and load necessary Java code. ```python jpype.startJVM(classpath=["lib/*", "classes"]) ``` -------------------------------- ### Cross-Platform GUI Environment Setup Source: https://jpype.readthedocs.io/en/latest/userguide.html Ensures GUI applications run correctly across macOS, Linux, and Windows by managing the GUI event loop. This is particularly important for Swing and JavaFX applications, and essential on macOS. ```python from jpype import setupGuiEnvironment from javafx.application import Platform def say_hello_later(): """Test function for scheduling a task on the JavaFX Application Thread.""" print("Hello from JavaFX!") def launch_gui(): """Launch the GUI application.""" # Example: Schedule a task on the JavaFX Application Thread Platform.runLater(say_hello_later) print("GUI launched") # Use setupGuiEnvironment to ensure cross-platform compatibility setupGuiEnvironment(launch_gui) ``` -------------------------------- ### Create Primitive Array in Java Source: https://jpype.readthedocs.io/en/latest/_sources/quickguide.rst.txt Demonstrates how to create a primitive integer array in Java using JPype. ```java int[] array = new int[5] ``` -------------------------------- ### Get HashMap Size Source: https://jpype.readthedocs.io/en/latest/_sources/quickguide.rst.txt Retrieve the number of key-value pairs in a HashMap. ```java int sz = myMap.size(); ``` ```python sz = len(myMap) ``` -------------------------------- ### JVM Functions Source: https://jpype.readthedocs.io/en/latest/_sources/api.rst.txt Functions to control and start the Java Virtual Machine (JVM). ```APIDOC ## JVM Functions ### Description Functions to control and start the Java Virtual Machine (JVM). ### Methods - `jpype.startJVM()` - `jpype.shutdownJVM()` - `jpype.getDefaultJVMPath()` - `jpype.getClassPath()` ### Decorators - `@jpype.onJVMStart` ``` -------------------------------- ### Create and Start a Daemon Java Thread Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Demonstrates how to create a Java thread and mark it as a daemon thread using JPype. This ensures the thread does not prevent the JVM from shutting down. ```python import java.lang.Thread # Create a Java thread thread = java.lang.Thread() # Mark the thread as daemon thread.setDaemon(True) # Start the thread thread.start() ``` -------------------------------- ### Java Interface Definition Source: https://jpype.readthedocs.io/en/latest/_sources/userguide.rst.txt Example of a Java interface that can be implemented by a Python proxy. ```java public interface ITestInterface2 { int testMethod(); String testMethod2(); } ```