Main Content

Pass Java Objects by Reference


MWJavaObjectRef, a special subclass of MWArray, can be used to create a MATLAB® array that references Java® objects. For detailed usage information on this class, constructor, and associated methods, see the MWJavaObjectRef page in the Javadoc or search for MWJavaObjectRef in the MATLAB Help browser Search field.

You can find the Javadoc at matlabroot/help/javabuilder/MWArrayAPI in your product installation.

Wrap and Pass Objects to MATLAB

You can create a MATLAB code wrapper around Java objects using MWJavaObjectRef. Using this technique, you can pass objects by reference to MATLAB functions, clone a Java object inside a generated package, as well as perform other object marshaling specific to the MATLAB Compiler SDK™ product. The examples in this section present some common use cases.

Passing a Java Object into a MATLAB Compiler SDK Java Method

To pass an object into a MATLAB Compiler SDK Java method:

  1. Use MWJavaObjectRef to wrap your object.

  2. Pass your object to a MATLAB function. For example:

            /* Create an object */
            java.util.Hashtable<String,Integer> hash = 
                              new java.util.Hashtable<String,Integer>();
            hash.put("One", 1);
            hash.put("Two", 2);
            System.out.println("hash: ");
            /* Create a MWJavaObjectRef to wrap this object */
            origRef = new MWJavaObjectRef(hash);
            /* Pass it to a MATLAB function that lists its methods, etc */
            result = theComponent.displayObj(1, origRef);            

Cloning an Object

You can also use MWJavaObjectRef to clone an object. Continuing with the example in Passing a Java Object into a MATLAB Compiler SDK Java Method, do the following:

  1. Add to the original hash.

  2. Clone the object.

  3. (Optional) Continue to add items to each copy. For example:

                origRef = new MWJavaObjectRef(hash);            
                result = theComponent.addToHash(1, origRef);
                outputRef = (MWJavaObjectRef)result[0];
                /* We can typecheck that the reference contains a      */
                /*        Hashtable but not <String,Integer>;          */
                /* this can cause issues if we get a Hashtable<wrong,wrong>. */
                java.util.Hashtable<String, Integer> outHash = 
                /* We've added items to the original hash, cloned it, */
                /* then added items to each copy */

For reference, here is the source code for addToHash.m:


function h2 = addToHash(h)

% Validate input
if ~isa(h,'java.util.Hashtable')
    error('addToHash:IncorrectType', ...
        'addToHash expects a java.util.Hashtable');

% Add an item
h.put('From MATLAB',12);
% Clone the Hashtable and add items to both resulting objects
h2 = h.clone();

Passing a Date into a Method and Getting a Date from a Method

In addition to passing in created objects, as in Passing a Java Object into a MATLAB Compiler SDK Java Method, you can also use MWJavaObjectRef to pass in Java utility objects such as To do so, perform the following steps:

  1. Get the current date and time using the Java object

  2. Create an instance of MWJavaObjectRef in which to wrap the Java object.

  3. Pass it to a MATLAB function that performs further processing, such as nextWeek.m. For example:

                /* Get the current date and time */
                java.util.Date nowDate = new java.util.Date();
                /* Create a MWJavaObjectRef to wrap this object */
                origRef = new MWJavaObjectRef(nowDate);
                /* Pass it to a MATLAB function that calculates one week */
                /* in the future */
                result = theComponent.nextWeek(1, origRef);
                outputRef = (MWJavaObjectRef)result[0];
                java.util.Date nextWeekDate = 
    For reference, here is the source code for nextWeek.m:


function nextWeekDate = nextWeek(nowDate)

% Validate input
if ~isa(nowDate,'java.util.Date')
    error('nextWeekDate:IncorrectType', ...
        'nextWeekDate expects a java.util.Date');

% Use java.util.Calendar to calculate one week later 
% than the supplied 
% java.util.Date
cal = java.util.Calendar.getInstance();
cal.add(java.util.Calendar.DAY_OF_MONTH, 7);
nextWeekDate = cal.getTime();

Returning Java Objects Using unwrapJavaObjectRefs

If you want actual Java objects returned from a method (without the MATLAB wrappering), use unwrapJavaObjectRefs.

This method recursively connects a single MWJavaObjectRef or a multidimensional array of MWJavaObjectRef objects to a reference or array of references.

The following code snippets show two examples of calling unwrapJavaObjectRefs:

Returning a Single Reference or Reference to an Array of Objects with unwrapJavaObjectRefs

             Hashtable<String,Integer> myHash =
                     new Hashtable<String,Integer>();
		      	myHash.put("a", new Integer(3));
      			myHash.put("b", new Integer(5));
      			MWJavaObjectRef A = 
                    new MWJavaObjectRef(new Integer(12));
      			System.out.println("A referenced the object: "
                     + MWJavaObjectRef.unwrapJavaObjectRefs(A));
      			MWJavaObjectRef B = new MWJavaObjectRef(myHash);
      			Object bObj = (Object)B;
      			System.out.println("B referenced the object: "
                  + MWJavaObjectRef.unwrapJavaObjectRefs(bObj))

Produces the following output:

             A referenced the object: 12
             B referenced the object: {b=5, a=3}

Returning an Array of References with unwrapJavaObjectRefs

             MWJavaObjectRef A = 
                      new MWJavaObjectRef(new Integer(12));
      			MWJavaObjectRef B = 
                      new MWJavaObjectRef(new Integer(104));
      			Object[] refArr = new Object[2];
      			refArr[0] = A;
      			refArr[1] = B;
      			Object[] objArr = 
      			System.out.println("refArr referenced the objects: " +
                             objArr[0] + " and " + objArr[1]);

Produces the following output:

             refArr referenced the objects: 12 and 104

Optimization Example Using MWJavaObjectRef

For a full example of how to use MWJavaObjectRef to create a reference to a Java object and pass it to a method, see Pass Java Objects to MATLAB.