[英]How can I get the instance of a static class which is initiated inside static block in servlet filter?
在我的 Servlet 中有一个对象 B 在加载时启动。 对象 B 的初始化在一个静态块中,如下所示:
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。过滤器 B 位于 web.xml 中的过滤器 A 之后,如下所示。
<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;
}
}
如果您要问如何使用反射对其进行编码,要点是:
像这样:
Field f = AIAItest.class.getField("bb");
f.setAccessible(true); // effectively make it public
BB bb = (BB)f.get(null);
鉴于b
在FilterA
是public
和static
的,对它的直接静态引用应该可以工作。 在FilterB
,此代码应该可以工作
B b = FilterA.b;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.