Wednesday, 22 September 2010

Getting the Interfaces Implemented by a Class using reflection in java

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 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 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.
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

No comments:

Post a Comment