The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: The Reflection API
Lesson: Examining Classes

Identifying the Interfaces Implemented by a Class

The type of an object is determined by not only its class and superclass, but also by its interfaces. In a class declaration, the interfaces are listed after the implements keyword. For example, the RandomAccessFile class implements the DataOutput and DataInput interfaces:
public class RandomAccessFile implements DataOutput, DataInput
You invoke the getInterfaces method to determine which interfaces a class implements. The getInterfaces method returns an array of Class objects. The reflection API represents interfaces with Class objects. Each Class object in the array returned by getInterfaces represents one of the interfaces implemented by the class. You can invoke the getName method on the Class objects in the array returned by getInterfaces to retrieve the interface names. To find out how to get additional information about interfaces, see the section Examining Interfaces.

The program that follows prints the interfaces implemented by the RandomAccessFile class.

import java.lang.reflect.*;
import java.io.*;

class SampleInterface {

   public static void main(String[] args) {
      try {
          RandomAccessFile r = new RandomAccessFile("myfile", "r");
          printInterfaceNames(r);
      } catch (IOException e) {
          System.out.println(e);
      }
   }

   static void printInterfaceNames(Object o) {
      Class c = o.getClass();
      Class[] theInterfaces = c.getInterfaces();
      for (int i = 0; i < theInterfaces.length; i++) {
         String interfaceName = theInterfaces[i].getName();
         System.out.println(interfaceName);
      }
   }
}
Note that the interface names printed by the sample program are fully qualified:
java.io.DataOutput
java.io.DataInput

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.