|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
If you aren't certain that a particular object is an array, you can check it with theClass.isArraymethod. Let's take a look at an example.The sample program that follows prints the names of the arrays that are encapsulated in an object. The program performs these steps:
- It retrieves the
Classobject that represents the target object.- It gets the
Fieldobjects for theClassobject retrieved in step 1.- For each
Fieldobject, the program gets a correspondingClassobject by invoking thegetTypemethod.- To verify that the
Classobject retrieved in the preceding step represents an array, the program invokes theisArraymethod.Here's the source code for the sample program:
The output of the sample program follows. Note that the left bracket indicates that the object is an array. For a detailed description of the type descriptors thatimport java.lang.reflect.*; import java.awt.*; class SampleArray { public static void main(String[] args) { KeyPad target = new KeyPad(); printArrayNames(target); } static void printArrayNames(Object target) { Class targetClass = target.getClass(); Field[] publicFields = targetClass.getFields(); for (int i = 0; i < publicFields.length; i++) { String fieldName = publicFields[i].getName(); Class typeClass = publicFields[i].getType(); String fieldType = typeClass.getName(); if (typeClass.isArray()) { System.out.println("Name: " + fieldName + ", Type: " + fieldType); } } } } class KeyPad { public boolean alive; public Button power; public Button[] letters; public int[] codes; public TextField[] rows; public boolean[] states; }getNamereturns, see section 4.3.1 of The Java Virtual Machine Specification.Name: letters, Type: [Ljava.awt.Button; Name: codes, Type: [I Name: rows, Type: [Ljava.awt.TextField; Name: states, Type: [Z
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.