Calling Java from MATLAB?

There are three cases to consider.

  1. Java built-in libraries.

    That is, anything described here. These items can simply be called directly. For example:

    map = java.util.HashMap;
    map.put(1,10);
    map.put(2,30);
    map.get(1)   %returns 10
    

    The only complication is the mapping Matlab performs between Matlab data types and Java data types. These mappings are described here (Matlab to Java) and here (Java to Matlab). (tl; dr: usually the mappings are as you would expect)

  2. Precompiled *.jar files

    You first need to add these to Matlab’s java class path. You can do this dynamically (that is, per-Matlab session, with no required Matlab state), as follows:

    javaaddpath('c:\full\path\to\compiledjarfile.jar')
    

    You can also add these statically by editing the classpath.txt file. For more information use docsearch java class path.

  3. Precompiled *.class files.

    These are similar to *.jar file, except you need to add the directory containing the class file, rather than the class files themselves. For example:

    javaaddpath('c:\full\path\to\directory\containing\class\files\')  
    %NOT THIS:  javaaddpath('c:\full\path\to\directory\containing\class\files\classname.class')
    

Leave a Comment