在我的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构建的... –