MATLAB Object-Oriented Programming

(Joyce) #1
function cbFunc(obj,varargin)
c = class(obj);
disp(['Java object callback on class ',c])
end
function delete(obj)
c = class(obj);
disp(['ML object destructor called for class ',c])
end
end
end

Suppose that you create a CallbackWithJava object from within a function:

function testDestructor
cwj = CallbackWithJava
...
end

Creating an instance of the CallbackWithJava class creates the
com.mathworks.jmi.Callback object and executes the callback function:

testDestructor

cwj =

CallbackWithJava with no properties.

Java object callback on class CallbackWithJava

The handle variable, cwj, exists only in the function workspace. However, MATLAB does
not call the class delete method when the function ends. The
com.mathworks.jmi.Callback object still exists and holds a reference to the object of
the CallbackWithJava class, which prevents destruction of the MATLAB object.

clear classes
Warning: Objects of 'CallbackWithJava' class exist. Cannot clear this class or
any of its superclasses.

To avoid causing inaccessible objects, call delete explicitly before losing the handle to
the MATLAB object.

function testDestructor
cwj = CallbackWithJava
...
delete(cwj)
end

7 Value or Handle Class — Which to Use

Free download pdf