/*
* file: MethodUsageDemo.java
* package: oreilly.hcj.reflection
*
* This software is granted under the terms of the Common Public License,
* CPL, which may be found at the following URL:
* http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
*
* Copyright(c) 2003-2005 by the authors indicated in the @author tags.
* All Rights are Reserved by the various authors.
*
########## DO NOT EDIT ABOVE THIS LINE ########## */
package oreilly.hcj.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.util.Locale;
import oreilly.hcj.bankdata.Gender;
import oreilly.hcj.bankdata.Person;
/**
* Demonstrates dynamic usage of methods.
*
* @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
* @version $Revision: 1.3 $
*/
public class MethodUsageDemo {
/** Date formatter to be used. */
static final DateFormat DATE_FORMATTER =
DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
/**
* Ouput the values of the "get" methods.
*
* @param obj The object to output.
*
* @throws InvocationTargetException If an error occurs in calling the get methods.
* @throws IllegalAccessException If the security manager rejects access.
*/
public static final void outputValues(final Object obj)
throws InvocationTargetException, IllegalAccessException {
final String PREFIX = "get"; //$NON-NLS-1$
System.out.println("--- Accessing Get Methods ---");
Method[] meths = obj.getClass()
.getMethods();
for (int idx = 0; idx < meths.length; idx++) {
if (meths[idx].getName()
.startsWith(PREFIX)) {
if (meths[idx].getParameterTypes().length == 0) {
System.out.print(meths[idx].getName() + " = "); //$NON-NLS-1$
System.out.println(meths[idx].invoke(obj, null));
}
}
}
}
/**
* Main method.
*
* @param args Command line arguments.
*
* @throws RuntimeException If an unforseen error occurs.
*/
public static void main(final String[] args) {
final Person person = new Person();
try {
person.setFirstName("Joe");
person.setLastName("Smith");
person.setGender(Gender.MALE);
person.setTaxID("0121FG12");
person.setBirthDate(DATE_FORMATTER.parse("01/12/1971"));
// Output the object.
outputValues(person);
outputValues(Gender.FEMALE);
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
}
/* ########## End of File ########## */
|