The type of an object is determined not only by its class and superclass, but also by its interfaces. In a class declaration, the interfaces are listed after the
The
To find out how to get additional information about interfaces, see Examining Interfaces.
The program that follows prints the interfaces implemented by the
implements
keyword. For example, the RandomAccessFile
class implements the DataOutput
and DataInput
interfaces: You invoke thepublic class RandomAccessFile implements DataOutput, DataInput
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 upon 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 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
No comments:
Post a Comment