Main Content

Pass Java Objects by Reference

MATLAB Array

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: ");
            System.out.println(hash.toString());
            
            /* 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);            
            MWArray.disposeArray(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);            
                System.out.println("hash:");
                System.out.println(hash.toString());
                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 = 
                          (java.util.Hashtable<String,Integer>)(outputRef.get());
                
                /* We've added items to the original hash, cloned it, */
                /* then added items to each copy */
                System.out.println("hash:");
                System.out.println(hash.toString());
                System.out.println("outHash:");
                System.out.println(outHash.toString());

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

addToHash.m

function h2 = addToHash(h)

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

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

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 java.util.date. To do so, perform the following steps:

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

  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();
                System.out.println("nowDate:");
                System.out.println(nowDate.toString());
                
                /* 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 = 
                      (java.util.Date)outputRef.get();
                System.out.println("nextWeekDate:");
                System.out.println(nextWeekDate.toString());
    For reference, here is the source code for nextWeek.m:

nextWeek.m

function nextWeekDate = nextWeek(nowDate)

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

% Use java.util.Calendar to calculate one week later 
% than the supplied 
% java.util.Date
cal = java.util.Calendar.getInstance();
cal.setTime(nowDate);
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 = 
                 MWJavaObjectRef.unwrapJavaObjectRefs(refArr);
      			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.