在我的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;
}
}
我對java servlets不太熟悉,但只需通過執行FilterA.b就可以訪問類B. – Himself12794
你可以修改FilterA的來源嗎? – Bohemian
不是真正的cuz FilterA是由第三方提供的JAR構建的... –