Creating and Using Java™ Objects

Overview

You create a Sun™ 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 can also 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

MATLAB displays information similar to:

myDate = 
Thu Aug 23 12:58:54 EDT 2007

All of the programming examples in this chapter contain Java object constructors. For example, the code in the Example — Reading a URL creates a java.net.URL object with the constructor:

url = java.net.URL(... 
     'http://archive.ncsa.uiuc.edu/demoweb/')

Using the javaObject Function

Under certain circumstances, you may need to use the javaObject 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 = javaObject('class_name',x1,...,xn);

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

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

With the javaObject function you can:

The default MATLAB constructor syntax requires that no segment of the input class name 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.) Any class name segment that exceeds namelengthmax characters is truncated by MATLAB. In the rare case where you need to use a class name of this length, you must use javaObject to instantiate the class.

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

class  = 'java.lang.String';
text = 'hello';
strObj = javaObject(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');

Java™ Objects Are References in MATLAB® Software 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. This happens if the object is changed by MATLAB code or by Java code.

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

MATLAB displays:

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 software to assemble the enclosed objects into a single object.

Concatenating Objects of the Same Class

If all of the objects being operated on are of the same Java class, the concatenation of those objects produces 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)

MATLAB displays:

ans = 
java.lang.Integer[]:
    [88]
    [45]

Concatenating Objects of Unlike Classes

When you concatenate objects of unlike classes, MATLAB finds one class from which all of the input objects inherit, and makes the output 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 java.lang.Number, since this is the common parent to the three input classes.

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

MATLAB displays:

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]

MATLAB displays:

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. Use the load function to load it back into MATLAB from that MAT-file. To save a Java object to a MAT-file, and to load the object from the MAT-file, make sure that the object and its class meet all of the following criteria:

If you define your own Java classes, or subclasses of existing classes, you can follow the criteria above to enable objects of the class to be saved and loaded in MATLAB. For details on defining classes to support serialization, consult your Java development documentation. (See also To Learn More About Java™ Programming Language.)

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')

MATLAB displays:

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 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 Example — Finding an 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 by referring to it in relation to the package and class names, java.lang.Integer, rather than an object instance.

thisType = java.lang.Integer(0).TYPE;

In MATLAB, you can use that same syntax. Or you can refer to the TYPE field in relation to 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

MATLAB displays:

thatType =
int

Assigning to a Static Field

You can assign values to static fields by using a static set method of the class, or by making the assignment in reference to 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 in reference to an instance of the class.

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

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)

MATLAB displays:

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 has the form:

x = isjava(obj)

isjava returns 1 if obj is a Java object, and 0 if it is not. For example, type:

isjava(value)

MATLAB displays:

ans =
     1

To find out if an object is an instance of a specified class, use the isa function, which has the form:

x = isa(obj, 'class_name')

isa returns 1 if obj is an instance of the class named 'class_name', and 0 if it is not. Note that 'class_name' can be a MATLAB built-in or user-defined class, as well as a Java class. For example, type:

isa(value, 'java.lang.Integer')

MATLAB displays:

ans =
     1
  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS