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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

2 Comments

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.
You are right, I misunderstood the question. Thanks for clarifying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.