Datasheet

}
public boolean testConcat()
{
String s1 = “test”;
String s2 = “ 123”;
return(concat(s1,s2).equals(“test 123”));
}
public boolean testSubstring()
{
String str = “The cat landed on its feet”;
return(substring(str, 4, 7).equals(“cat”));
}
}
Following is an example implementation of the testing framework. It uses reflection to process the anno-
tation and then invoke the testing methods, writing the results to the screen (though other output desti-
nations can be built into the framework).
import java.lang.reflect.*;
import java.lang.annotation.*;
import java.util.*;
public class TestFramework {
static void executeTests(String className) {
try {
Object obj = Class.forName(className).newInstance();
TestParameters tp = obj.getClass().getAnnotation(TestParameters.class);
if(tp != null) {
String methodList = tp.testMethods();
StringTokenizer st = new StringTokenizer(methodList, “,”);
while(st.hasMoreTokens()) {
String methodName = st.nextToken().trim();
Method m = obj.getClass().getDeclaredMethod(methodName);
System.out.println(“”);
System.out.println(methodName);
System.out.println(“----------------”);
String result = invoke(m, obj);
System.out.println(“Result: “ + result);
}
} else {
System.out.println(“No annotation found for “ + obj.getClass());
}
} catch(Exception ex) {
System.out.println(“Exception: “ + ex);
ex.printStackTrace();
}
}
static String invoke(Method m, Object o) {
33
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 33