I have a custom Java library in MATLAB R2024b, more specifically a JAR file, that lives in Git. Anytime I switch Git branches, the JAR file changes, and I am unable to unload the original JAR even though the old path to the JAR does not exist.
I have tried to remove the path via the function "javarmpath" and have tried commands such as "clear all". These do not seem to address the issue, only restarting MATLAB seems to resolve it. How can I unload JAR files without having to restart MATLAB everytime?

 Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 6 Apr. 2026

0 Stimmen

It is possible to unload Java libraries in MATLAB, but only if they are the dynamic path. In order to be on the dynamic path, the JAR file has to be added via the "javaaddpath" function, and can be verified after running "javaclasspath('dynamic')" in the MATLAB Command Window. For more information regarding this process, please refer to the following MATLAB Documentation page about MATLAB's dynamic path and how to add and remove Java libraries from the path.
Once you have verified that the JAR is on the dynamic path, you can use the sample script below to unload a Java library:
>> javarmpath("path_to_jar_file") %Remove the JAR file from the Java class path
>> clear java %Clear the workspace and java class definitions from memory
>> java.lang.System.gc(); %Request Java to perform garbage collection
>> java.lang.System.runFinalization(); %Request Java to run finalization
It is important to note that "java.lang.System.gc()" is not guaranteed to unload a Java library. Due to Java Virtual Machine's internal resource management, as users, we can only request, not force, garbage collection and finalization. Consequently, "java.lang.System.gc()" may have to be run multiple times to achieve the desired result.

Weitere Antworten (0)

Kategorien

Produkte

Version

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by