2011年2月15日 星期二

JAVA: 在 JSTL 中使用 EL 取 Java Class 裡的 Constants (解惑)

在上一篇提到我在工作上遇到了個需要用 EL 來取得 Java Class 裡面的常數的問題,並提供了我找到的幾個解決方法。
後來在經過一番 Trace 過後,發現了原來我們的專案已經使用了第一個方法,而第一個方法(
在 JSTL 中取用 Java constants)裡面呢…限制了只有宣告成 final 的constants才會被放進map...


if (Modifier.isFinal(modifier) && !Modifier.isPrivate(modifier))
    try {
        this.put(field.getName(), field.get(this));
    }catch (IllegalAccessException e) {}

因為這個 if ,所以沒有宣告成 final 的 constants 不能在 jsp 上以 EL 來取得了…囧

=====

在與同事描述了這個結論時,發現了我們只是繼承 JSTL 並沒有去呼叫 JSTLConstants 的 constructor ,為什麼會去執行上面的程式碼呢?
於是我們猜想會不會是 java 幫我們做了 super() 這件事… 

測試:
父類別
public class TestParent {    public TestParent() {
System.out.println("parent...start"); System.out.println("parent...end");
    }
}

子類別
public class TestChild extends TestParent {
    public TestChild() {
        System.out.println("child...start");
System.out.println("child...end");
    }

     public static void main(String[] args) {
new TestChild();
    }
} 

執行子類別的結果:
parent...start
parent...end
child...start
child...end 

果然自動執行了父類別的 constructor ...XDDDD

沒有留言:

張貼留言