MATLAB: How should I include a JAR file in the compiled application with MATLAB Compiler 4.1 (R14SP1)

MATLAB Compiler

I use a Java class in my MATLAB code functions, either as a JDBC driver with Database Toolbox or using the MATLAB Java interface to create instances of the java class directly. When I compile my functions with MATLAB compiler, the Java classes cannot be located. With Database Toolbox I get the error message
JDBC Driver Error: oracle.jdbc.driver.OracleDriver. Driver Not Found/Loaded.
when using the MATLAB Java interface I receive the error
??? Undefined variable "oracle" or class "oracle.jdbc.driver.OracleDriver".

Best Answer

In order to use a Java class in a compiled application, the JAR-file which contains the class or the CLASS-file need to be available on the deployment machine and the JAR-file or directory which contains the CLASS-file or package hierarchy need to be on the Java classpath in the deployed application.
The -a flag to the MCC command provides a simple mechanism to accomplish both of these requirements. When a JAR-file or CLASS-file is added with the -a flag, it will be added to the CTF-archive and when the application starts up, that JAR-file or CLASS-file will also be automatically added to the dynamic java classpath. If you are using DEPLOYTOOL instead of the MCC command, you can add the JAR-file or CLASS-file to the "Other files" folder.
The java classpath in the compiled application will not get updated correctly if you are using a CLASS-file which is part of a package but which is not in a JAR-file. This is because there is no way for DEPLOYTOOL or MCC to determine that the CLASS-file is part of a package. In this case you will need to manually modify the java classpath in the compiled application, for example by using JAVAADDPATH.