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
  • Marcel (9 days 13 hours ago): Hi, I am trying to set the legend to Static, but this command seems not to work in R2022a anymore: set(gca,’LegendColorbarL isteners’,[]); Any ideas? THANKS / marcel
  • Gres (9 days 17 hours ago): In 2018b, you can get the icons by calling [hh,icons,plots,txt] = legend({‘Line 1’});
  • Yair Altman (11 days 12 hours ago): @Mitchell – in most cases the user wants a single string identifier for the computer, that uniquely identifies it with a distinct fingerprint that is different from any...
  • Mitchell (11 days 20 hours ago): Great post! I’m not very familiar with the network interfaces being referenced here, but it seems like the java-based cross-platform method concatenates all network...
  • Yair Altman (14 days 14 hours ago): Dani – You can use jViewport.setViewPosition(java .awt.Point(0,0)) as I showed in earlier comments here
  • dani (15 days 9 hours ago): hi!! how i can set the horizontal scrollbar to the leftside when appearing! now it set to right side of text
  • Yair Altman (24 days 6 hours ago): Dom – call drawnow *just before* you set hLine.MarkerHandle.FaceColorTy pe to 'truecoloralpha'. Also, you made a typo in your code: it’s truecoloralpha, not...
  • Dom (25 days 4 hours ago): Yair I have tried your code with trucoloralpha and the markers do not appear transparent in R2021b, same as for Oliver.
  • Yair Altman (28 days 12 hours ago): Ren – This is usually the expected behavior, which avoids unnecessary duplications of the Excel process in CPU/memory. If you want to kill the process you can always run...
  • Yair Altman (29 days 2 hours ago): When you use plot() without hold(‘on’), each new plot() clears the axes and draws a new line, so your second plot() of p2 caused the first plot() line (p1) to be...
  • Cesim Dumlu (35 days 9 hours ago): Hello. I am trying to do a gradient plot for multiple functions to be displayed on the same axes and each one is colorcoded by respective colordata, using the same scaling. The...
  • Yair Altman (43 days 12 hours ago): @Veronica – you are using the new version of uitree, which uses HTML-based uifigures, and my post was about the Java-based uitree which uses legacy Matlab figures. For...
  • Veronica Taurino (43 days 12 hours ago): >> [txt1,txt2] ans = ‘abrakadabra’
  • Veronica Taurino (43 days 13 hours ago): Hello, I am just trying to change the uitree node name as you suggested: txt1 = 'abra'; txt2 = 'kadabra'; node.setName([txt1,txt2]); >> "Unrecognized method, property, or...
  • Yair Altman (46 days 13 hours ago): The version of JGraph that you downloaded uses a newer version of Java (11) than the one that Matlab supports (8). You need to either (1) find an earlier version of JGraph that...
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