importing java classes in matlab classdef

2019-08-02 09:16发布

I have a matlab class defined using classdef.

I'm creating a wrapper for some java stuff and need to import several classes.

I can't figure out where to import these classes, so far I can import them as needed in each method... which is painful.

any ideas?

3条回答
做自己的国王
2楼-- · 2019-08-02 09:30

Both answers are not correct (anymore?). You can assign the imported classes to a property of the classobject and access them without reimporting. The following code works just fine (tested in Matlab 2016a):

classdef moveAndClick < handle
    properties (Access = private)
        mouse;
        leftClick;
    end

    methods
        %% Constructor
        function obj = moveAndClick()
            import java.awt.Robot;
            import java.awt.event.InputEvent;
            obj.mouse = Robot;
            obj.leftClick = InputEvent.BUTTON1_MASK;
        end

        %% Destructor
        function delete (~)
        end

        function moveClick (obj, positionX, positionY)
            % move mouse to requested position
            obj.mouse.mouseMove(positionX, positionY);

            % click on the current position
            obj.mouse.mousePress(obj.leftClick);
            obj.mouse.mouseRelease(obj.leftClick);
        end
    end
end
查看更多
孤傲高冷的网名
3楼-- · 2019-08-02 09:31

A small test confirms that you need to repeat the import list in every method:

classdef MyClass < handle
    properties
        s
    end
    methods
        function obj = MyClass()
            import java.lang.String
            obj.s = String('str');
        end
        function c = func(obj)
            c = String('b');      %# error: undefined function 'String'
        end
    end
end
查看更多
Melony?
4楼-- · 2019-08-02 09:35

Yes, you need to import them into each method, which is painful.

查看更多
登录 后发表回答