70 likes | 168 Views
Reflection and Annotations. The idea of reflection is that java system can look at the classes in its system and discover features about them. You can find methods, access variables, etc.
E N D
The idea of reflection is that java system can look at the classes in its system and discover features about them. You can find methods, access variables, etc. Reflection is an example of metaprogramming which exists in a lot of programming languages (especially higher level ones).
Example: Unit Tests Imagine you want to write a class that tests some code you’re writing. You want to have several methods each of which test a particular feature. Then you have code that looks like this: public static void printTest(String name, boolean passed) { System.out.print (“Test for “ + name + “: “); if(passed) System.out.println(“passed.”); else System.out.println(“failed.”); } public void runAllTests() { printTest(“Feature A”, testFeatureA()); printTest(“Feature B”, testFeatureB()); printTest(“Feature C”, testFeatureC()); //it sure is annoying to keep adding things to this list }
Activity • Using reflection write a method runAllTests() which an makes an object run every method it has that begins with the word “test”. • If you finish that, improve it so it only runs test methods that take an String as a parameter, and passes each test the string “Reflection Is So Cool” • Use Java’s reflection tutorial to get yourself started – it’s linked off the resources section of Sakai
General Guides for Reflection • Never use reflection when using basic OO techniques would do • Be aware that reflection often can often cause seemingly innocuous changes to break your code • Very slow
Annotations • You can declare a special thing called an annotation. The annotation can be applied to classes, methods, fields…whatever you like. It looks like this: @MyMethodAnnotation public void myMethod() { … } • Annotations can even take parameters • Makes metaprogramming more explicit (e.g. rather than relying on methods named “testXYZ” you can look for methods annotated with the “@Test” annotation • Some annotations only exist at compile time (they exist for compilers or other tools that look at source code) • Some annotations exist at runtime to be discovered by reflection
Activity • Build your own @CoolTest annotation that takes string testDescription as a parameter • Make a new function runAllAnnotatedTests() that runs all annotated tests but prints their descriptions beforehand • Use the Annotation tutorial linked off the resources section in Sakai • When you are finished, submit your code via ambient