public class MyCalculator { boolean isReady; @TOFORMATE double concurrency; @TOFORMATE Date debitDate; public MyCalculator() { super(); }
@TODO public void calculateRate(){ System.out.println("Calculating..."); } }
清單15動態查找注釋
public class TestCalculator { public static void main(String[] args) { MyCalculator cal = new MyCalculator(); cal.calculateRate(); try { Class c = cal.getClass(); Method[] methods = c.getDeclaredMethods();
for (Method m: methods) { // 判定這個方法有沒有使用TODO if (m.isAnnotationPresent(TODO.class)) System.out.println("Method "+m.getName()+": the TODO is present"); }
Field[] fields = c.getDeclaredFields(); for (Field f : fields) { // 判定這個域有沒有使用TOFORMATE if (f.isAnnotationPresent(TOFORMATE.class)) System.out.println ("Field "+f.getName()+": the TOFORMATE is present"); } } catch (Exception exc) { exc.printStackTrace(); } } }
圖7種給出visit方法的實現是一個簡單的例子。假如要實現輸出成xml格式的,可以定義Exporter子類:XMLExporter。假如希望輸出成文本的可以定義TXTExporter。但是這樣做不夠靈活的地方在于,假如Employee加入其他的域變量,那么相應的visitor類也需要進行修改。這就違反了面向對象Open for Extension, close for Modification的原則。