Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Reflection: A New Way to Discover Information about Java classes

By Dan Becker
2003-05-24


Querying Interfaces Using Java 1.02

The first improvement that you can make to the program is to list the interfaces a class implements as well as the classes it extends. This is done with the Class getInterfaces() method, which is available in Java 1.02 or later. The "Print Interfaces" loop added to the printTypes(...) method below recursively prints the types that a class implements.


public void printType( Class type, int depth ) {
// Calculate indent and proper class label
StringBuffer indent = new StringBuffer();
for (int i = 0; i < depth; i++ ) indent.append( " " );
String[] labels = ( depth == 0 ? basic : extended );
System.out.print( indent + labels[ type.isInterface() ? 1 : 0 ] + " " );

// Print class name
System.out.println( type.getName() );
// Recurse super classes
if ( type.getSuperclass() != null ) // true for all except java.lang.Object
printType( type.getSuperclass(), depth + 1 );

// Print interfaces this class implements.
Class[] interfaces = type.getInterfaces();
for (int i = 0; i < interfaces.length; i++ )
printType( interfaces[ i ], depth + 1 );
}

private final static String[]
basic = { "class", "interface" },
extended = { "extends", "implements" };

This example also contains "pretty printing" code that indents the output and prints a label "class" or "interface" to distinguish the two. Notice that within the first print statement I have added the isInterface() method to perform this check. At this point, all methods used in the program are available in Java 1.02.



Tutorial Pages:
» Introduction
» Outlining the Class Hierarchy Using Java 1.02
» Querying Interfaces Using Java 1.02
» An Improved Java 1.02 Reflection Program
» Using the Reflection Features of Java 1.1: Modifiers
» Using the Reflection Features of Java 1.1: Fields
» Security Issues
» Conclusion


First published by IBM DeveloperWorks


 | Bookmark
Related Tutorials:
» All about JAXP, Part 1
» Make Database Queries Without the Database
» Load List Values for Improved Efficiency
» 2 Ways To Implement Session Tracking
» A Simple Way to Read an XML File in Java
» Develop Aspect-Oriented Java Applications with Eclipse and AJDT