2

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?

chappjc
  • 30,359
  • 6
  • 75
  • 132
danatron
  • 667
  • 1
  • 9
  • 19

3 Answers3

3

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

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64
1

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
Amro
  • 123,847
  • 25
  • 243
  • 454
0

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
  • 1
    You are wrong. What you assign to the property is an object **instance** (created through an empty-argument constructor). You are then simply referring to this object instance, which has nothing to do with class imports. If you want to create another `Robot()` instance in `moveClick`, you have to import the class again. – nirvana-msu Jun 29 '16 at 22:02
  • You are right, I misunderstood the question. Thanks for clarifying. – Raimund Schlüßler Jun 30 '16 at 16:08