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


Using the Reflection Features of Java 1.1: Modifiers

The first bit of information you can obtain from the additional reflection features is the scope and visibility of a given class. To do this, you have to import the new java.lang.reflect package with an import statement at the beginning of the program. You also use the new getModifiers() method of the Class class. This adds one line to the middle of the printType method, right before you print the class name. You are using a static method from the new Modifier class to convert the modifiers of a class to a String that can be printed by a program.


import java.lang.reflect.*;

public void printType( Class type, int depth ) {
...

// Print class modifiers
System.out.print( Modifier.toString( type.getModifiers() ) + " " );

// Print class name
System.out.println( type.getName() );

...
}

This modification results in the output shown below. Notice the classes and interfaces now list their visibility (public) and other modifiers such as synchronized, final, or abstract.



[c:\]java Inspector java.lang.Integer
class public final synchronized java.lang.Integer
extends public abstract synchronized java.lang.Number
extends public synchronized java.lang.Object
implements public interface java.io.Serializable
[c:\]_


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

Ask A Question
characters left.