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