HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

"What is Java Reflection?"
Vol. 6, Issue 9, p. 72


Listing 1

java.awt.Point p = new java.awt.Point(10,20);
Class pointClass = p.getClass();                          
// You could call Point.class as well
Field xField = pointClass.getField( "x" );
xField.setInt( p, 3 );  // Set receives an object as its second parameter,
                        // we have to wrap the 3
System.out.println( p.x );                                      
// Will print 3

Listing 2

Class[] parameterTypes = new Class[]{String.class};
Object[] parameterValues = new Object[]{"this line was printed using Reflection"};
// Get the class for System.out
Class class = System.out.getClass();
Method printlnMethod = class.getMethod( "println", parameterTypes );
printlnMethod.invoke( System.out, parameterValues );            
// The string is printed here

Listing 3

Class[] parameterTypes= new Class[]{Integer.TYPE, Integer.TYPE,
Object[] parameters = new Object[]{new Integer( 255 ), new
  Integer( 0 ), new Integer( 0 )};

Class colorClass = Class.forName( "java.awt.Color" );
Constructor colorConstructor = colorClass.getConstructor
  ( parameterTypes );

Object myRedColor = colorConstructor.newInstance( parameters );

Listing 4

try {
// Try to get the method myMethod () from the class of the
      object myObject
        Method myMethod = anObject.getClass().getMethod
   ( "myMethod", new Class[]{} );
// Invoke the method
        myMethod.invoke( myObject, new Object[]{} );
catch ( NoSuchMethodException nSchMetE ) {}
// Thrown by getMethod if the method is not found
catch ( SecurityException secE ) {}
// Thrown by the security manager to indicate a security violation
catch ( IllegalAccessException illAccE ) {}
// Thrown if current method does not have access to myMethod
catch ( IllegalArgumentException illArgE ){}
// Thrown if an argument passed is inappropriate
catch ( InvocationTargetException iTarE) {}
// Thrown if myMethod throws an exception, you can call
//  iTarE.getTargetException() to get the exception.


All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.