Accessing internal Java class members

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=...]

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]

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.

Categories: Java, Low risk of breaking in future versions, Undocumented feature

Tags: ,

Bookmark and SharePrint Print

4 Responses to Accessing internal Java class members

  1. Martin Lechner says:

    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)
  2. Grunde says:

    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 says:

      Ignore this :)

    • 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

Your email address will not be published. Required fields are marked *