Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Accessing internal Java class members

August 12, 2015 4 Comments

Following my previous post on using the Java classloader, I thought I’d follow up today with a somewhat-related peculiarity.

Inner classes

Whenever we have an enum or inner-class defined within a Java class, it can be accessed in Java using standard dot-notation. For example, com.mathworks.hg.peer.ComboboxPeer.MLComboBox refers to an inner class MLComboBox which is defined within the ComboboxPeer class. When compiled, the class would be stored in a file called ComboboxPeer$InnerClassName.class. In other words, the JVM uses the $ separator char to indicate that MLComboBox is internal to ComboboxPeer.
Within the Java code, we would simply use the regular dot-notation (ClassName.MLComboBox) – the $ separator is part of the internal JVM implementation that the Java programmer should not be concerned about.
Unfortunately, we cannot ignore this in Matlab: Matlab’s interpreter, which acts as a bridge to the JVM, is not smart enough to know that in certain cases the dot-notation should be converted into a $. Therefore, trying to access ClassName.MLComboBox directly in Matlab fails:

>> jObject = com.mathworks.hg.peer.ComboboxPeer.MLComboBox([])
Undefined function or variable 'MLComboBox'.
 
>> jObject = com.mathworks.hg.peer.ComboboxPeer$MLComboBox([])
 jObject = com.mathworks.hg.peer.ComboboxPeer$MLComboBox([])
                                             ↑
Error: The input character is not valid in MATLAB statements or expressions.

The solution in such cases is to use Matlab’s javaObject (or javaObjectEDT) function with the JVM’s internal $-representation:

>> jObject = javaObject('com.mathworks.hg.peer.ComboboxPeer$MLComboBox',[])
jObject =
com.mathworks.hg.peer.ComboboxPeer$MLComboBox[,0,0,0x0,invalid,layout=com.mathworks.hg.peer.types.HGWindowsComboBoxUI$1,alignmentX=...]

>> jObject = javaObject('com.mathworks.hg.peer.ComboboxPeer$MLComboBox',[]) jObject = com.mathworks.hg.peer.ComboboxPeer$MLComboBox[,0,0,0x0,invalid,layout=com.mathworks.hg.peer.types.HGWindowsComboBoxUI$1,alignmentX=...]


To access public methods (functions) of the inner class, we could similarly use the javaMethod (or javaMethodEDT) function.

Enumerations

Java Enums act in a very similar manner to inner classes: we access them using standard dot-notation in Java source code, and the JVM translates the enumerations into $-notation internally. Unfortunately, we cannot access Java enums in Matlab using javaObject as shown above; we need to use a more circuitous way.
For example, JVM 1.6 (in Matlab 7.5 R2007b onward) provides access to the new TrayIcon object (I explained its usage back in 2009). One of TrayIcon‘s functionalities is displaying a message next to the tray icon, using java.awt.TrayIcon.displayMessage(). This method expects an object of type java.awt.TrayIcon.MessageType, which is an enumeration within the TrayIcon class. However, Matlab’s dot-notation does not recognize what should have been the following correct notation, so we need to resort to Java reflection:

>> trayIcon.displayMessage('title','info msg',TrayIcon.MessageType.INFO);
??? No appropriate method or public field MessageType for class java.awt.TrayIcon
>> trayIconClasses = trayIcon.getClass.getClasses;
>> trayIconClasses(1)
ans =
class java.awt.TrayIcon$MessageType	<= hurray!!!
>> MessageTypes = trayIconClasses(1).getEnumConstants
MessageTypes =
java.awt.TrayIcon$MessageType[]:
    [java.awt.TrayIcon$MessageType]	<= 1: ERROR
    [java.awt.TrayIcon$MessageType]	<= 2: WARNING
    [java.awt.TrayIcon$MessageType]	<= 3: INFO
    [java.awt.TrayIcon$MessageType]	<= 4: NONE
>> trayIcon.displayMessage('title','info msg',MessageTypes(3));

systray INFO message

and another example, now with a WARNING icon:
systray WARNING message

We can also access Java enums using their built-in values() and valueOf() methods:

>> msgType=javaMethod('valueOf','java.awt.TrayIcon$MessageType','INFO')
msgType =
INFO		<= a java.awt.TrayIcon$MessageType object
 
>> enums = cell(javaMethod('values','java.awt.TrayIcon$MessageType'));
>> msgType = enums{3};   % alternative way to find the INFO enum value
>> cellfun(@(c)c.toString.char, enums, 'uniform',false)'
ans =
    'ERROR'    'WARNING'    'INFO'    'NONE'

Inner classes can also be accessed using the Java classloader, although this is more cumbersome.

Static fields

Using public Java static fields in Matlab is easy – in most cases we could use standard dot-notation. For example:

>> jColor = java.awt.Color.orange
jColor =
java.awt.Color[r=255,g=200,b=0]

>> jColor = java.awt.Color.orange jColor = java.awt.Color[r=255,g=200,b=0]

We could use the struct function to get a Matlab struct with all the public static fields of a Java class object:

>> struct(java.awt.Color.red)
ans =
          white: [1x1 java.awt.Color]
          WHITE: [1x1 java.awt.Color]
      lightGray: [1x1 java.awt.Color]
     LIGHT_GRAY: [1x1 java.awt.Color]
           gray: [1x1 java.awt.Color]
           GRAY: [1x1 java.awt.Color]
       darkGray: [1x1 java.awt.Color]
      DARK_GRAY: [1x1 java.awt.Color]
          black: [1x1 java.awt.Color]
          BLACK: [1x1 java.awt.Color]
            red: [1x1 java.awt.Color]
            RED: [1x1 java.awt.Color]
           pink: [1x1 java.awt.Color]
           PINK: [1x1 java.awt.Color]
         orange: [1x1 java.awt.Color]
          ...

But in some cases, we may have static fields of an uninstantiable inner class, and in such cases dot-notation will fail in Matlab. Moreover, since the inner class is not instantiable, we cannot use javaObject as above.
For example, trying to access internal static fields in java.nio.channels.FileChannel.MapMode, in order to use them to create a memory-mapped file using FileChannel.map(…), is problematic. In this specific case, we have the built-in memmapfile Matlab function as a much simpler alternative, but for the record, we could do this:

>> channel = java.io.FileInputStream('234.jpg').getChannel
channel =
sun.nio.ch.FileChannelImpl@1c7a5d3    <= which extends FileChannel
 
>> innerClasses = channel.getClass.getSuperclass.getDeclaredClasses;
>> innerClasses(1)
ans =
class java.nio.channels.FileChannel$MapMode
 
>> read_only_const = innerClasses(1).getField('READ_ONLY').get(1)
read_only_const =
READ_ONLY    <= a java.nio.channels.FileChannel$MapMode object
 
>> fields = innerClasses(1).getFields;
>> read_only_const = fields(1).get(1);    % an alternative
 
>> buffer = channel.map(read_only_const, 0, channel.size);

Additional information can be found in my book, Undocumented Secrets of MATLAB-Java Programming (CRC Press, 2011). If you already have this book, please be kind enough to post a review on Amazon, to spread the word.

Related posts:

  1. Java class access pitfalls – There are several potential pitfalls when accessing Matlab classes from Matlab. ...
  2. Extending a Java class with UDD – Java classes can easily be extended in Matlab, using pure Matlab code. ...
  3. A couple of internal Matlab bugs and workarounds – A couple of undocumented Matlab bugs have simple workarounds. ...
  4. Matlab's internal memory representation – Matlab's internal memory structure is explored and discussed. ...
  5. Performance: accessing handle properties – Handle object property access (get/set) performance can be significantly improved using dot-notation. ...
  6. Accessing plot brushed data – Plot data brushing can be accessed programmatically using very simple pure-Matlab code...
Java Undocumented feature
Print Print
« Previous
Next »
4 Responses
  1. Martin Lechner August 13, 2015 at 06:29 Reply

    Thank you for the very good information to use Java from Matlab.
    I have the problem the Matlab normally casts all scalar primitive data types to double. This is OK for the most types except long. For big long numbers (> 4.5e15) this would lead to round off errors (e.g. eps(2^63-1) = 2048). Only Java arrays of type long are converted to Matlab int64 arrays.
    We filled a Bug report and they forwarded this issue to the developer team (typical for Matlab and we have no information what they are really doing).

    Unfortunately my college Andreas J. found the following work around solution:
    cast method call with int64

    format long 
    longMax = int64(java.lang.Long.MAX_VALUE)

    format long longMax = int64(java.lang.Long.MAX_VALUE)

  2. Grunde November 5, 2015 at 04:11 Reply

    Hi,
    I’m trying to access a Static variable in a Java Interface. More specifically org.orekit.utils.Constants.WGS84_EARTH_EQUATORIAL_RADIUS. Is it possible from Matlab?

    URL: https://www.orekit.org/site-orekit-7.0/apidocs/org/orekit/utils/Constants.html

    • Grunde November 5, 2015 at 04:29 Reply

      Ignore this 🙂

    • Yair Altman November 5, 2015 at 04:33 Reply

      You can only access public static variables. The javadoc that you provided does not list this variable as public, but this does not necessarily mean that it is not. The easiest way would be to test it in Matlab directly. I promise that it will not crash your computer…

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (email)
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
ActiveX (6) AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Iñigo (2 days 11 hours ago): Thanks Yair. I didn’t realize it was posted just above. It would be great to know about a solution soon
  • Yair Altman (3 days 19 hours ago): @Iñigo – your query is related to Seth’s question above. We can access the currently-browsed URL in JavaScript (for example: jBrowserPanel.executeScript...
  • Iñigo (5 days 10 hours ago): I am looking for setting a UI that allows following process: opening a web site, navigate inside this web site and at some specific moments (i.e. when the figure is closed or a button...
  • Nicholas (12 days 16 hours ago): Yair, this works wonderfully! I can’t thank you enough!
  • Collin (14 days 20 hours ago): Seth Good point, I am using 2022b, mathworks seems to have started using CEF browsers from 2019a, best I can tell. take a look at the package com.mathworks.toolbox.matla...
  • Seth (15 days 12 hours ago): Collin, What version of MATLAB are you using?
  • Collin (20 days 18 hours ago): Seth, I have had some success executing javascript that requires no return value by executing it directly (sort of) on the org.cef.browser.CefBrowser that a...
  • Coo Coo (22 days 13 hours ago): FFT-based convolution is circular whereas MATLAB’s conv functions have several options (‘valid’, ‘same’, ‘full’) but unfortunately not...
  • Seth (22 days 16 hours ago): No luck with removing the space.
  • Seth (22 days 18 hours ago): The javascript code works fine running the application from the 2019b desktop version and the 2016b deployed version.
  • Seth (22 days 18 hours ago): I have been using this browser functionality in 2016b because it works fully in deployed applications in that version. However, because of Java 7 being flagged as a security risk, I...
  • Yair Altman (22 days 18 hours ago): I’ve never tested javascript callbacks, but perhaps you should try removing the extra space after the “matlab:” protocol specifier. Does it make any difference?
  • Seth (22 days 18 hours ago): I have been using this functionality in 2016b since it works in deployed applications and have not had a reason to need to upgrade but with java 7 being flagged as a security risk I am...
  • KEVIN (42 days 19 hours ago): I apologize, I intended my response to fall under ‘T’ but did not seem to work. I was referring to the bit of code posted by ‘T’ regarding the toolgroup and...
  • Yair Altman (42 days 19 hours ago): It is not clear from your comment which code exactly you are referring to and what you see differently in 19b vs. 20b, so I cannot assist with your specific query. In general I...
Contact us
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top