MATLAB Answers

2

Cannot call java class from Matlab

Asked by Tobias Elmøe on 2 May 2012
Hi all. I have a peculiar problem. I am trying to use a java class in Matlab. I have made a very simple java Hello World example:
public class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
After compiling (using jdk1.7.0_04 - the 64 bit version), I use the javaaddpath to direct Matlab to the custom class folder, in my case 'c:\temp\javaclass\' so I write:
javaaddpath('c:\temp\javaclass\')
I then try to create an object
Hello = HelloWorldApp()
but I get the error
Undefined function or variable 'HelloWorldApp'.
I have spent hours now trying to figure it out, I've read the tutorial sevaral times, I have tried looking for answers at Mathworks Answers, but nothing has helped so far. Can anyone point out the reason for my failure?

  0 Comments

Sign in to comment.

Tags

Products

1 Answer

Answer by Oleg Komarov on 2 May 2012

I tried your example but I added the path manually to $matlabroot\toolbox\local\classpath.txt (on a new line simply add):
C:\java\
Then start MATLAB and check the path with javaclasspath.
Finally call HelloWorldApp
Warning: A Java exception occurred trying to load the HelloWorldApp class:
Java exception occurred:
java.lang.UnsupportedClassVersionError: HelloWorldApp : Unsupported major.minor
version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at
com.mathworks.jmi.OpaqueJavaInterface.findClass(OpaqueJavaInterface.java:470)

  3 Comments

Problem solved: it was a wrong version of the jdk (1.7.0_04). After installing version 1.6.0_31 and compiling again, I was able to add the java object, after adding invoking the javaaddpath command first.
Hurray for totally obscurred (non)error messages. That cost me 3 hours of frustration.
This technical note shows how to use the latest java version:
http://www.mathworks.co.uk/support/solutions/en/data/1-1812J/
Indeed, MATLAB uses a 1.6.x version of Java, so you need to use some 1.6.x as well (as you did 1.6.0_31).

Sign in to comment.