Documentation Center

  • Trial Software
  • Product Updates

Creating and Using Java Objects

Overview

You create a Java® object in the MATLAB® workspace by calling one of the constructors of that class. You then use commands and programming statements to perform operations on these objects. You also can save your Java objects to a MAT-file and, in subsequent sessions, reload them into MATLAB.

Constructing Java Objects

You construct Java objects in the MATLAB workspace by calling the Java class constructor, which has the same name as the class. For example, the following constructor creates a myDate object:

myDate = java.util.Date
myDate = 
Thu Aug 23 12:58:54 EDT 2007

MATLAB displays information for your system.

Using the javaObjectEDT Function

Under certain circumstances, use the javaObjectEDT function to construct a Java object. The following syntax invokes the Java constructor for class, class_name, with the argument list that matches x1,...,xn, and returns a new object, J.

J = javaObjectEDT('class_name',x1,...,xn);

For example, to construct and return a Java object of class java.lang.String, type:

strObj = javaObjectEDT('java.lang.String','hello');

With the javaObjectEDT function you can:

  • Use classes that have names that exceed the maximum length of a MATLAB identifier. (Call the namelengthmax function to obtain the maximum identifier length.)

  • Specify the class for an object at run time, for example, as input from an application user

The default MATLAB constructor syntax requires that no segment of the input class name can be longer than namelengthmax characters. (A class name segment is any portion of the class name before, between, or after a dot. For example, there are three segments in class, java.lang.String.) MATLAB truncates any class name segment that exceeds namelengthmax characters. In the rare case where you use a class name of this length, use javaObjectEDT to instantiate the class.

The javaObjectEDT function also allows you to specify the Java class for the object being constructed at run time. In this situation, you call javaObjectEDT with a string variable in place of the class name argument.

class  = 'java.lang.String';
text = 'hello';
strObj = javaObjectEDT(class, text);

In the usual case, when the class to instantiate is known at development time, it is more convenient to use the MATLAB constructor syntax. For example, to create a java.lang.String object, type:

strObj = java.lang.String('hello');

Use the javaObjectEDT function instead of the Java Class.forName method. For example, replace the following statement:

java.lang.Class.forName('xyz.myapp.MyClass')

with:

javaObjectEDT('xyz.myapp.MyClass')

    Note:   Typically, you do not need to use javaObjectEDT. The default MATLAB syntax for instantiating a Java class is simpler and is preferable for most applications. Use javaObjectEDT primarily for the previously described cases.

Java Objects Are References in MATLAB Applications

In MATLAB, Java objects are references and do not adhere to MATLAB copy-on-assignment and pass-by-value rules. For example:

myDate = java.util.Date;
setHours(myDate,10)
newDate = myDate;

In this example, the variable newDate is a reference to myDate, not a copy of the object. Any change to the object referenced by newDate also changes the object at myDate. Either MATLAB code or Java code might change the object.

The following example shows that myDate and newDate are references to the same object. When you change the hour via one reference (newDate), the change is reflected through the other reference (myDate), as well.

setHours(newDate,8)
myDate.getHours
ans =
     8

Concatenating Java Objects

You can concatenate Java objects in the same way that you concatenate native MATLAB types. You use either the cat function or the [ ] operators to tell MATLAB to assemble the enclosed objects into a single object.

Concatenating Objects of the Same Class

If concatenate objects of the same Java class, the concatenation is an array of objects from the same class.

In the following example, the cat function concatenates two objects of the class java.awt.Integer. The class of the result is also java.awt.Integer.

value1 = java.lang.Integer(88);
value2 = java.lang.Integer(45);
cat(1, value1, value2)
ans = 
java.lang.Integer[]:
    [88]
    [45]

Concatenating Objects of Unlike Classes

If you concatenate objects of unlike classes, MATLAB finds one class from which all of the input objects inherit. The concatenation is an instance of this class. MATLAB selects the lowest common parent in the Java class hierarchy as the output class.

For example, concatenating objects of java.lang.Byte, java.lang.Integer, and java.lang.Double creates an object of the common parent to the three input classes, java.lang.Number.

byte = java.lang.Byte(127);
integer = java.lang.Integer(52);
double = java.lang.Double(7.8);
[byte; integer; double]
ans =
java.lang.Number[]:
    [   127]
    [    52]
    [7.8000]

If there is no common, lower-level parent, then the resultant class is java.lang.Object, which is the root of the entire Java class hierarchy.

byte = java.lang.Byte(127);
point = java.awt.Point(24,127);
[byte; point]
ans =
java.lang.Object[]:
    [               127]
    [1x1 java.awt.Point]

Saving and Loading Java Objects to MAT-Files

Use the save function to save a Java object to a MAT-file. To load it back into MATLAB from that MAT-file, use the load function. When you save or load a Java object, the object and its class must meet all of the following criteria.

  • The class implements the Serializable interface (part of the Java API), either directly or by inheriting it from a parent class. Any embedded or otherwise referenced objects must also implement Serializable.

  • The definition of the class is not changed between saving and loading the object. Any change to the data fields or methods of a class prevents the loading (deserialization) of an object that was constructed with the old class definition.

  • Either the class does not have any transient data fields, or the values in transient data fields of the object to be saved are not significant. Values in transient data fields are never saved with the object.

If you define your own Java classes, or subclasses of existing classes, follow this criteria to enable saving and loading objects of the class in MATLAB. For details on defining classes to support serialization, consult your Java development documentation.

Finding the Public Data Fields of an Object

To list the public fields that belong to a Java object, use the fieldnames function, which takes either of these forms.

names = fieldnames(obj)
names = fieldnames(obj,'-full')

Calling fieldnames without -full returns the names of all the data fields (including inherited) on the object. With the -full qualifier, fieldnames returns the full description of the data fields defined for the object, including type, attributes, and inheritance information.

For example, create an Integer object with the command:

value = java.lang.Integer(0);

To see a full description of the data fields of value, type:

fieldnames(value,'-full')
ans = 
    'static final int MIN_VALUE'
    'static final int MAX_VALUE'
    'static final java.lang.Class TYPE'
    'static final int SIZE'

Accessing Private and Public Data

Java API classes provide accessor methods you can use to read from and, where allowed, to modify private data fields. These methods are sometimes referred to as get and set methods, respectively.

Some Java classes have public data fields, which your code can read or modify directly. To access these fields, use the syntax object.field.

Examples

The java.awt.Frame class provides an example of access to both private and public data fields. This class has the read accessor method getSize, which returns a java.awt.Dimension object. The Dimension object has data fields height and width, which are public and therefore directly accessible. For example, to access this data, type:

frame = java.awt.Frame;
frameDim = getSize(frame);
height = frameDim.height;
frameDim.width = 42;

The programming examples in this chapter also contain calls to data field accessors. For instance, the sample code for Find Internet Protocol Address uses calls to accessors on a java.net.InetAddress object.

hostname = address.getHostName; 
ipaddress = address.getHostAddress;

Accessing Data from a Static Field

In a Java language program, a static data field is a field that applies to an entire class of objects. Static fields are most commonly accessed in relation to the class name itself. For example, the following code accesses the TYPE field of the Integer class using the package and class names, java.lang.Integer.

thisType = java.lang.Integer.TYPE;

In MATLAB, you can use that same syntax. Or you can refer to the TYPE field as an instance of the class. The following example creates an instance of java.lang.Integer called value, and then accesses the TYPE field using the name value rather than the package and class names.

value = java.lang.Integer(0);
thatType = value.TYPE
thatType =
int

Assigning to a Static Field

Assign values to static fields using the static set method of the class. Alternatively, assign values using an instance of the class. For more information, see Accessing Data from a Static Field. You can assign value to the field staticFieldName in the following example by referring to this field as an instance of the class.

objectName = java.className;
objectName.staticFieldName = value;

    Note:   MATLAB does not allow assignment to static fields using the class name itself.

Determining the Class of an Object

To find the class of a Java object, use the query form of the class function. After execution of the following example, myClass contains the name of the package and class that the object value instantiates.

value = java.lang.Integer(0);
myClass = class(value)
myClass =
java.lang.Integer

Because this form of class also works on MATLAB objects, it does not, in itself, tell you whether it is a Java class. To determine the type of class, use the isjava function, which returns 1 if obj is a Java object, and 0 if it is not. For example, type:

isjava(value)
ans =
     1

To find out if an object is an instance of a specified class, use the isa function. The class can be a MATLAB built-in or user-defined class, as well as a Java class. For example, type:

isa(value, 'java.lang.Integer')
ans =
     1
Was this topic helpful?