2016-09-14 22 views
1

在我的Servlet中有一個對象B在加載時啓動。對象B的初始化處於如下靜態塊中:如何獲得在servlet過濾器中的靜態塊內啓動的靜態類的實例?

FilterA implements Filter{ 
    private static B b = new B(); 
    static {b.setText("This is B");} 
    doFilter(){...} 
} 

class B{ 
    private String text; 
    public void setText(String s){ 
     this.text=s; 
    } 
    public String getText(){ 
     return this.text; 
    } 
} 

其中FilterA是web.xml中定義的Servlet過濾器。

我正在做的是編寫一個新的Servlet過濾器(filterB)來修改對象B. filterB放在web.xml中的filterA之後,如下所示。

<filter> 
    <filter-name>filterA</filter-name> 
    <filter-class>my.FilterA</filter-class> 
</filter> 
<filter> 
    <filter-name>filterB</filter-name> 
    <filter-class>my.FilterB</filter-class> 
</filter> 

鑑於反思是我可以在濾波器B用於檢索的B類的實例唯一的解決辦法是有什麼方法,可以採用以找回?

我不認爲Class.forName()適用於這種情況,因爲我不打算創建任何類B的新實例,但僅用於檢索現有實例。

//新的東西放在這裏

我寫一個簡單的測試類來模擬這種情況。請把下面的代碼作爲點:

package com.jm.test; 

public class AIAItest { 

    private static BB bb = new BB(); 

    static{ 
     bb.setText("sb"); 
    } 

    public static void main(String[] args){ 
     try { 

      //TODO use reflection to get the instance of BB, is it possible? 
      //do not simply refer to bb 


     } catch (Exception e) { 
      e.printStackTrace(); 
     } 


    } 
} 

class BB{ 
    private String text; 

    public String getText() { 
     return text; 
    } 

    public void setText(String text) { 
     this.text = text; 
    } 

} 
+1

我對java servlets不太熟悉,但只需通過執行FilterA.b就可以訪問類B. – Himself12794

+0

你可以修改FilterA的來源嗎? – Bohemian

+0

不是真正的cuz FilterA是由第三方提供的JAR構建的... –

回答

0

鑑於bFilterApublicstatic,直接靜態引用它應該工作。在FilterB,此代碼應工作

B b = FilterA.b; 
+0

thx爲你的答案第一。這是我寫的公開的錯誤,實際上應該是私人的。這就是爲什麼我正在考慮反思的解決方案。 –

1

如果你問如何使用反射代碼時,要點是:

  • 對於靜態字段,不存在需要Field實例。 get()方法
  • 你必須讓業界人士

像這樣:

Field f = AIAItest.class.getField("bb"); 
f.setAccessible(true); // effectively make it public 
BB bb = (BB)f.get(null); 
+0

thx。這正是我想要的...... :) –