Understanding Java Callbacks / Events in Matlab

I try to understand more fundamentally what happens when adding listeners in Matlab to java objects. See here for an original discussion.

Below is java src to configure callback

public class Handler {

    public Listener object;

    public class Event extends java.util.EventObject {
        public double d1,d2,d3;
        Event(Object obj, double d1, double d2, double d3) {
            super(obj); this.d1 = d1; this.d2 = d2; this.d3 = d3;
        }}

    public interface Listener extends java.util.EventListener {
        // the function call matlab proxy obj implements
        void measurement(Event event);
    }

    public void addListener   (Listener listener) {
        System.out.println("listener has been added");
        this.object = listener;
    }

    public void removeListener(Listener listener) {
        System.out.println("listener has been removed");
        this.object = null;
    }

    // wrapper function (i.e. what actually exposed/called/used)
    public void measurement(double temp, double pressure, double height) {
        this.object.measurement( new Event(this, temp, pressure, height) );
        System.out.println("listener has been notified");
    }
}

Then in Matlab (2014b), you can configure the Java β†’ Matlab callback as

% create Handler java object in matlab
handler = com.callback.Handler();

% add a listener for interface function measurement(e)
addlistener(handler,'measurement',@(h,e)disp(e.d1+e.d2+e.d3));

% call the wrapper function manually to test setup
handler.measurement(1,2,3);

Some idea of ​​initial setup of Matlab call addlisteneris done

 /toolbox/matlab/uitools/private/javaaddlistener.m

When called addlistenerin Matlab, I get a message in the command window that

Added

listener

from function addlistenerc Handler. So here Matlab dynamically created an object that implements the interface Listenerand called

handler.addListener(mysteryObj);

I can see what Matlab puts with

>> handler.object

which returns

com.mathworks.MLEventAdapters.com.callback.Handler$ListenerLIAdapterClass@45a37759

, , proxy?

, , >> handler.object,

? , Matlab

handler.removeListener(mysteryObj) 

?

, com.mathworks.jmi, , , ... .

+4

All Articles