Examining Classes |
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 theimplements
keyword. For example, theRandomAccessFile
class implements theDataOutput
andDataInput
interfaces:You invoke thepublic class RandomAccessFile implements DataOutput, DataInputgetInterfaces
method to determine which interfaces a class implements. ThegetInterfaces
method returns an array ofClass
objects. The reflection API represents interfaces withClass
objects. EachClass
object in the array returned bygetInterfaces
represents one of the interfaces implemented by the class. You can invoke thegetName
method on theClass
objects in the array returned bygetInterfaces
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.Note that the interface names printed by the sample program are fully qualified: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); } } }java.io.DataOutput java.io.DataInput
Examining Classes |