I have some MATLAB code and some Java code that need to talk with each other. I was getting a NoSuchMethodError. When I pass a MATLAB double array to a Java method that accepts double[] argument.
So I write a simple ‘hello world’ to get the class of an object passed to the method
public void printArray(Object array) { System.out.println(array.getClass()); System.out.println(array.getClass().getPackage()); }
Calling this method from MATLAB, I get this interesting output:
>> a.printArray(2) class java.lang.Double package java.lang >> a.printArray('hello') class java.lang.String package java.lang >> a.printArray(true) class java.lang.Boolean package java.lang >> a.printArray([2 3 4]) class [D null >> a.printArray([true false]) class [Z null
Can someone explain whats happening. I have MATLAB R14 and the Java class is compiled with 1.3 compatibility.
I think the original problem has been updated by the OP, so I’ll take the chance to summarize our findings so far:
We have established that the sample code in the original question produces the expected behavior. MATLAB passes data as primitives to Java, and Java performs the appropriate autoboxing to Objects. As pointed out in Matthew Simoneau’s reply, MATLAB explains how it matches its data types to Java data types in the ‘Passing Data to a Java Method‘ section of its documentation. The surprising thing is that a single MATLAB data type may match different Java data types, e.g.
logicalmatchesboolean,byte,short,int,long,float, anddouble, in that order of precedence.The
NoSuchMethodErrorthat the OP initially encountered was caused by the use of a wrong method. This is no longer a problem. Usingdouble[]as the method argument works.The ‘strange’ class names (
[Dand[Z) are actually notations used by Java to describe arrays of primitive types. The API explains the usage in Class.getName().Case closed =)