How to avoid ambiguity when calling Java from Matlab?

淺唱寂寞╮ 提交于 2020-01-02 15:45:43

问题


I just discovered that when calling Java from Matlab

object.method(arg1,...,argn)

is equivalent to

method(object, arg1,...,argn)

The problem here is I also have a method.m that does some translation from Java to Matlab (eg. convert String[] to cell of strings). My method.m looks like

function result = method(object, arg1,...argn)
  intermediate = object.method(arg1,...argn);
  result = translate(intermediate);

What is happening is when I call method(object, arg1,...,argn), it does the direct Java call, instead of my using my method.m

The fix is easy, just don't use the same method name for both my Java methods and my .m files. But is there another way? How do I know which method will be called given the same name? Is there a way to ensure I call method.m instead of the Java method? Its easy to ensure a call to the Java method, just use the object.method syntax.

As a side note, what is also silly is the .m Editor links to the method.m on the method(object, arg1,...,argn) call, while when it debugs it calls the Java method.


回答1:


You may be running into some problems with how MATLAB does dispatching...

How do I know which method will be called given the same name?

This section of the MATLAB documentation discusses how a function is chosen in cases when there are multiple functions with the same name. From the documentation: "The function precedence order determines the precedence of one function over another based on the type of function and its location on the MATLAB path." This order (from highest to lowest) is given below:

  • Subfunction
  • Private function
  • Class constructor
  • Overloaded method
  • Function in current directory
  • Function elsewhere on the path

The placement of your "method.m" function will likely determine if it gets called or the Java method gets called when using the "method(object,...)" syntax.

Is there a way to ensure I call method.m instead of the Java method?

Right now, I'm guessing your "method.m" is in the current directory or elsewhere on the path (the two lowest precedence positions to be in). If you made "method.m" a subfunction in the larger code calling it, or if it's possible to put it in a private directory where it can be called by every function that needs to call it, then it may get called instead of the Java method when you use the "method(object,...)" syntax.

Hope this helps!




回答2:


Hmmmmmmmmm.... you could try obtaining a function handle using @method and then call feval() on the function handle.

That might work but I'm not sure....



来源:https://stackoverflow.com/questions/656014/how-to-avoid-ambiguity-when-calling-java-from-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!