MATLAB: Is some of the Java code being executed even though I am not executing the section of MATLAB code which calls it from MATLAB

MATLAB

I have a Java class which I am going to be calling from MATLAB. The only place where I call the Java class from is in a sub-function in my MATLAB file. Right now I am never calling that sub-function because the Java class has some errors in it. However, when I execute the main function in the MATLAB file, it appears that some of the Java code in that class is being executed.
Specifically it appears that "clinit" (the function which initializes a class when a Java class is loaded) is being called to execute the static blocks and initialize static data. This only seems to happen the first time the file is called.
For example I have the following code in my MATLAB file:
function mainfun
disp 'mainfun'
function subfun
disp 'subfun'
x=work.StaticError();
and when I call mainfun I receive the following message ERROR: Warning: A Java exception occurred trying to load the work.StaticError class: Java exception occurred: java.lang.UnsatisfiedLinkError: Expecting an absolute path of the library: nolib at java.lang.Runtime.load0(Unknown Source) at java.lang.System.load(Unknown Source) at work.StaticError.<clinit>(StaticError.java:8)

Best Answer

Having a reference to a Java class or an IMPORT statement which imports that class anywhere in a MATLAB file will cause the MATLAB interpreter to load that class when the file is first loaded. If a Java class has a static block, that code will be executed when the class is loaded. If there is an error in the static block of code, an error will occur. This loading happens on a per-file bases (not on a function basis) so the main function and all sub-functions and nested-functions will all be parsed and java classes loaded at the same time. This is expected and required behavior for the MATLAB interpreter to be able to resolve java class names.
In order to prevent the Java classes from being loaded and prevent their static blocks from being executed, you will need to separate out any of the calls to the Java class into a separate file which is never accessed.